{{- include "openwork-ee.customCa.validate" . }}
{{- if .Values.migrations.enabled }}
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "openwork-ee.fullname" . }}-migrate
  labels:
    {{- include "openwork-ee.componentLabels" (dict "root" . "component" "migration") | nindent 4 }}
  {{- if .Values.migrations.hook }}
  annotations:
    "helm.sh/hook": pre-install,pre-upgrade
    "helm.sh/hook-weight": "-5"
    {{- with .Values.migrations.hookDeletePolicy }}
    "helm.sh/hook-delete-policy": {{ . | quote }}
    {{- end }}
  {{- end }}
spec:
  backoffLimit: {{ .Values.migrations.backoffLimit }}
  activeDeadlineSeconds: {{ .Values.migrations.activeDeadlineSeconds }}
  template:
    metadata:
      labels:
        {{- include "openwork-ee.componentSelectorLabels" (dict "root" . "component" "migration") | nindent 8 }}
      {{- with .Values.migrations.podAnnotations }}
      annotations:
        {{- toYaml . | nindent 8 }}
      {{- end }}
    spec:
      restartPolicy: Never
      {{- with .Values.imagePullSecrets }}
      imagePullSecrets:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- if .Values.customCa.enabled }}
      volumes:
        {{- include "openwork-ee.customCa.volume" . | nindent 8 }}
      {{- end }}
      containers:
        - name: migrate
          image: "{{ .Values.denApi.image.repository }}:{{ default .Values.image.tag .Values.denApi.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          {{- if .Values.customCa.enabled }}
          volumeMounts:
            {{- include "openwork-ee.customCa.volumeMount" . | nindent 12 }}
          {{- end }}
          command:
            {{- toYaml .Values.migrations.command | nindent 12 }}
          args:
            {{- toYaml .Values.migrations.args | nindent 12 }}
          env:
            - name: DB_MODE
              value: {{ .Values.config.databaseMode | quote }}
            - name: DATABASE_URL
              {{- if .Values.secret.create }}
              value: {{ .Values.secret.values.databaseUrl | quote }}
              {{- else }}
              valueFrom:
                secretKeyRef:
                  name: {{ include "openwork-ee.secretName" . }}
                  key: {{ .Values.secret.keys.databaseUrl }}
              {{- end }}
            - name: DEN_DB_ENCRYPTION_KEY
              {{- if .Values.secret.create }}
              value: {{ .Values.secret.values.denDbEncryptionKey | quote }}
              {{- else }}
              valueFrom:
                secretKeyRef:
                  name: {{ include "openwork-ee.secretName" . }}
                  key: {{ .Values.secret.keys.denDbEncryptionKey }}
              {{- end }}
            {{- if .Values.customCa.enabled }}
            {{- include "openwork-ee.customCa.env" . | nindent 12 }}
            {{- end }}
          {{- with .Values.migrations.resources }}
          resources:
            {{- toYaml . | nindent 12 }}
          {{- end }}
{{- end }}
