---
# Runs the schema migration once per sync, before the Deployment rolls, so the
# serve replicas never race migrations. Deleted before each re-create so a new
# image/version re-runs it.
#
# Sync-phase hook at wave 1 (NOT PreSync): the CNPG Cluster + generated
# postgres-app Secret apply at wave 0 and ArgoCD waits for the Cluster to be
# Healthy before starting wave 1, so on a fresh install Postgres exists before
# migrate connects. (A PreSync hook would run before the Sync phase that creates
# the DB, deadlocking the first install.)
apiVersion: batch/v1
kind: Job
metadata:
  name: ghp-migrate
  namespace: ghp
  annotations:
    argocd.argoproj.io/hook: Sync
    argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
    argocd.argoproj.io/sync-wave: "1"
spec:
  backoffLimit: 6
  ttlSecondsAfterFinished: 600
  template:
    metadata:
      labels:
        app: ghp-migrate
    spec:
      serviceAccountName: default
      automountServiceAccountToken: true
      restartPolicy: Never
      securityContext:
        runAsNonRoot: true
        runAsUser: 65532
        runAsGroup: 65532
        fsGroup: 65532
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: migrate
          image: ghcr.io/goodtune/ghp:0.20.0
          imagePullPolicy: IfNotPresent
          command: ["/ghp", "migrate"]
          env:
            - name: GHP_DATABASE_DRIVER
              value: postgres
            - name: GHP_DB_USER
              valueFrom:
                secretKeyRef:
                  name: postgres-app
                  key: username
            - name: GHP_DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: postgres-app
                  key: password
            - name: GHP_DATABASE_DSN
              value: "postgres://$(GHP_DB_USER):$(GHP_DB_PASSWORD)@postgres-rw.ghp.svc:5432/ghp?sslmode=require"
          volumeMounts:
            - name: tmp
              mountPath: /tmp
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop:
                - ALL
          resources:
            limits:
              cpu: "1"
              memory: 512Mi
            requests:
              cpu: 250m
              memory: 256Mi
      volumes:
        # Writable scratch: root FS is read-only, so give the migrator a /tmp.
        - name: tmp
          emptyDir:
            sizeLimit: 256Mi
