---
# Applies the arrproxy schema once per sync, before the api rolls, so the serve
# replicas never race migrations (arrproxy-api does not self-migrate). Runs as the
# CNPG-minted app user so the tokens table is owned by that role.
#
# Sync-phase hook at wave 1 (NOT PreSync): the CNPG Cluster + generated
# arrproxy-db-app Secret apply at wave 0 and ArgoCD waits for the Cluster to be
# Healthy before starting wave 1, so Postgres exists before migrate connects.
apiVersion: batch/v1
kind: Job
metadata:
  name: arrproxy-migrate
  namespace: arrstack
  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: arrproxy-migrate
    spec:
      serviceAccountName: default
      automountServiceAccountToken: false
      restartPolicy: Never
      securityContext:
        runAsNonRoot: true
        runAsUser: 65532
        runAsGroup: 65532
        fsGroup: 65532
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: migrate
          image: docker.io/library/postgres:18-alpine
          imagePullPolicy: IfNotPresent
          env:
            - name: HOME
              value: /tmp
            - name: PGUSER
              valueFrom:
                secretKeyRef:
                  name: arrproxy-db-app
                  key: username
            - name: PGPASSWORD
              valueFrom:
                secretKeyRef:
                  name: arrproxy-db-app
                  key: password
            - name: PGHOST
              value: arrproxy-db-rw.arrstack.svc.cluster.local
            - name: PGPORT
              value: "5432"
            - name: PGDATABASE
              value: arrproxy
            - name: PGSSLMODE
              value: require
          command:
            - psql
            - -v
            - ON_ERROR_STOP=1
            - -f
            - /migrations/0001_init.sql
          volumeMounts:
            - name: migrations
              mountPath: /migrations
              readOnly: true
            - name: tmp
              mountPath: /tmp
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop:
                - ALL
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: 500m
              memory: 256Mi
      volumes:
        - name: migrations
          configMap:
            name: arrproxy-migrations
        - name: tmp
          emptyDir:
            sizeLimit: 64Mi
