{{- if .Values.migrations.enabled }}
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "orchard.fullname" . }}-migrations
  labels:
    {{- include "orchard.labels" . | nindent 4 }}
  annotations:
    "helm.sh/hook": post-install,post-upgrade
    "helm.sh/hook-weight": "-5"
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
  template:
    metadata:
      labels:
        {{- include "orchard.selectorLabels" . | nindent 8 }}
    spec:
      {{- with .Values.imagePullSecrets }}
      imagePullSecrets:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      restartPolicy: Never
      initContainers:
        - name: wait-for-db
          image: "{{ .Values.initContainer.image.repository }}:{{ .Values.initContainer.image.tag }}"
          imagePullPolicy: {{ .Values.initContainer.image.pullPolicy }}
          command: ['sh', '-c', 'until nc -z {{ include "orchard.postgresql.host" . }} 5432; do echo waiting for database; sleep 2; done;']
      containers:
        - name: migrations
          image: "{{ .Values.migrations.image.repository }}:{{ .Values.migrations.image.tag | default .Chart.AppVersion }}"
          command: ["/bin/sh", "-c"]
          args:
            - |
              # The orchard-server automatically runs migrations on startup
              # This job just verifies connectivity
              echo "Database is ready at {{ include "orchard.postgresql.host" . }}:5432"
          env:
            - name: ORCHARD_DATABASE_HOST
              value: {{ include "orchard.postgresql.host" . | quote }}
            - name: ORCHARD_DATABASE_PORT
              value: {{ .Values.orchard.database.port | quote }}
            - name: ORCHARD_DATABASE_USER
              value: {{ .Values.orchard.database.user | default .Values.postgresql.auth.username | quote }}
            - name: ORCHARD_DATABASE_DBNAME
              value: {{ .Values.orchard.database.dbname | default .Values.postgresql.auth.database | quote }}
            - name: ORCHARD_DATABASE_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ include "orchard.postgresql.secretName" . }}
                  key: {{ include "orchard.postgresql.passwordKey" . }}
  backoffLimit: 3
{{- end }}
