# Database migration Job — runs `alembic upgrade head` once before
# the API and Worker Deployments start.  Helm hooks ensure ordering:
# the Job runs during pre-upgrade/pre-install and the Deployments wait
# for it via the `helm.sh/hook-weight` annotation.
{{- if .Values.migrations.enabled }}
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "docuelevate.fullname" . }}-migrate-{{ .Release.Revision }}
  namespace: {{ .Release.Namespace }}
  labels:
    {{- include "docuelevate.labels" . | nindent 4 }}
    app.kubernetes.io/component: migrate
  annotations:
    "helm.sh/hook": pre-install,pre-upgrade
    "helm.sh/hook-weight": "-5"
    "helm.sh/hook-delete-policy": before-hook-creation
    {{- if .Values.migrations.ttlSecondsAfterFinished }}
spec:
  ttlSecondsAfterFinished: {{ .Values.migrations.ttlSecondsAfterFinished }}
    {{- end }}
spec:
  {{- if .Values.migrations.ttlSecondsAfterFinished }}
  ttlSecondsAfterFinished: {{ .Values.migrations.ttlSecondsAfterFinished }}
  {{- end }}
  backoffLimit: 3
  template:
    metadata:
      labels:
        {{- include "docuelevate.selectorLabels" . | nindent 8 }}
        app.kubernetes.io/component: migrate
    spec:
      restartPolicy: OnFailure
      serviceAccountName: {{ include "docuelevate.serviceAccountName" . }}
      {{- with .Values.image.imagePullSecrets }}
      imagePullSecrets:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      containers:
        - name: migrate
          image: {{ include "docuelevate.image" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          command: ["alembic", "upgrade", "head"]
          envFrom:
            - configMapRef:
                name: {{ include "docuelevate.fullname" . }}-config
            - secretRef:
                name: {{ include "docuelevate.fullname" . }}-secret
          {{- with .Values.workdir.persistence }}
          volumeMounts:
            - name: workdir
              mountPath: /workdir
          {{- end }}
          resources:
            requests:
              cpu: 100m
              memory: 256Mi
            limits:
              cpu: 500m
              memory: 512Mi
      volumes:
        - name: workdir
          {{- if .Values.workdir.persistence.enabled }}
          persistentVolumeClaim:
            claimName: {{ .Values.workdir.persistence.existingClaim | default (printf "%s-workdir" (include "docuelevate.fullname" .)) }}
          {{- else }}
          emptyDir: {}
          {{- end }}
{{- end }}
