apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "graphql.fullname" . }}-database-migration
  labels:
    {{- include "graphql.labels" . | nindent 4 }}
  annotations:
    "helm.sh/hook": post-install,pre-upgrade
    "helm.sh/hook-weight": "-1"
    "helm.sh/hook-delete-policy": before-hook-creation

spec:
  template:
    spec:
      serviceAccountName: {{ include "graphql.serviceAccountName" . }}
      containers:
      - name: {{ .Chart.Name }}
        image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
        command: ["yarn", "predeploy"]
        env:
          - name: NODE_ENV
            value: "{{ .Values.env }}"
          - name: AFFINE_ENV
            value: "{{ .Release.Namespace }}"
          - name: DATABASE_PASSWORD
            valueFrom:
              secretKeyRef:
                name: pg-postgresql
                key: postgres-password
          {{ if not .Values.global.database.gcloud.enabled }}
          - name: DATABASE_URL
            value: postgres://{{ .Values.global.database.user }}:$(DATABASE_PASSWORD)@{{ .Values.global.database.url }}:{{ .Values.global.database.port }}/{{ .Values.global.database.name }}
          {{ end }}
          {{ if .Values.global.database.gcloud.enabled }}
          - name: DATABASE_URL
            value: postgres://{{ .Values.global.database.user }}:$(DATABASE_PASSWORD)@{{ .Values.global.database.gcloud.cloudSqlInternal }}:{{ .Values.global.database.port }}/{{ .Values.global.database.name }}
          {{ end }}
          {{ if .Values.app.objectStorage.r2.enabled }}
          - name: R2_OBJECT_STORAGE_ACCOUNT_ID
            valueFrom:
              secretKeyRef:
                name: "{{ .Values.app.objectStorage.r2.secretName }}"
                key: accountId
          - name: R2_OBJECT_STORAGE_ACCESS_KEY_ID
            valueFrom:
              secretKeyRef:
                name: "{{ .Values.app.objectStorage.r2.secretName }}"
                key: accessKeyId
          - name: R2_OBJECT_STORAGE_SECRET_ACCESS_KEY
            valueFrom:
              secretKeyRef:
                name: "{{ .Values.app.objectStorage.r2.secretName }}"
                key: secretAccessKey
          {{ end }}
        resources:
          requests:
            cpu: '100m'
            memory: '200Mi'
      restartPolicy: Never
  backoffLimit: 1
