apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "attune.fullname" . }}-migrations
  labels:
    {{- include "attune.labels" . | nindent 4 }}
    app.kubernetes.io/component: migrations
  annotations:
    helm.sh/hook: post-install,post-upgrade
    helm.sh/hook-weight: "-20"
    helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
spec:
  ttlSecondsAfterFinished: {{ .Values.jobs.migrations.ttlSecondsAfterFinished }}
  template:
    metadata:
      labels:
        {{- include "attune.componentLabels" (dict "root" . "component" "migrations") | nindent 8 }}
    spec:
      restartPolicy: OnFailure
      {{- if .Values.global.imagePullSecrets }}
      imagePullSecrets:
        {{- toYaml .Values.global.imagePullSecrets | nindent 8 }}
      {{- end }}
      containers:
        - name: migrations
          image: {{ include "attune.image" (dict "root" . "image" .Values.images.migrations) }}
          imagePullPolicy: {{ .Values.images.migrations.pullPolicy }}
          envFrom:
            - secretRef:
                name: {{ include "attune.secretName" . }}
          env:
            - name: MIGRATIONS_DIR
              value: /migrations
          resources:
            {{- toYaml .Values.jobs.migrations.resources | nindent 12 }}
---
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "attune.fullname" . }}-init-user
  labels:
    {{- include "attune.labels" . | nindent 4 }}
    app.kubernetes.io/component: init-user
  annotations:
    helm.sh/hook: post-install,post-upgrade
    helm.sh/hook-weight: "-10"
    helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
spec:
  ttlSecondsAfterFinished: {{ .Values.jobs.initUser.ttlSecondsAfterFinished }}
  template:
    metadata:
      labels:
        {{- include "attune.componentLabels" (dict "root" . "component" "init-user") | nindent 8 }}
    spec:
      restartPolicy: OnFailure
      {{- if .Values.global.imagePullSecrets }}
      imagePullSecrets:
        {{- toYaml .Values.global.imagePullSecrets | nindent 8 }}
      {{- end }}
      containers:
        - name: init-user
          image: {{ include "attune.image" (dict "root" . "image" .Values.images.initUser) }}
          imagePullPolicy: {{ .Values.images.initUser.pullPolicy }}
          envFrom:
            - secretRef:
                name: {{ include "attune.secretName" . }}
          command: ["/bin/sh", "-ec"]
          args:
            - |
              until PGPASSWORD="$DB_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -tAc "SELECT to_regclass('${DB_SCHEMA}.identity')" | grep -q identity; do
                echo "waiting for database schema";
                sleep 2;
              done
              exec /init-user.sh
          resources:
            {{- toYaml .Values.jobs.initUser.resources | nindent 12 }}
---
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "attune.fullname" . }}-init-packs
  labels:
    {{- include "attune.labels" . | nindent 4 }}
    app.kubernetes.io/component: init-packs
  annotations:
    helm.sh/hook: post-install,post-upgrade
    helm.sh/hook-weight: "0"
    helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
spec:
  ttlSecondsAfterFinished: {{ .Values.jobs.initPacks.ttlSecondsAfterFinished }}
  template:
    metadata:
      labels:
        {{- include "attune.componentLabels" (dict "root" . "component" "init-packs") | nindent 8 }}
    spec:
      restartPolicy: OnFailure
      {{- if .Values.global.imagePullSecrets }}
      imagePullSecrets:
        {{- toYaml .Values.global.imagePullSecrets | nindent 8 }}
      {{- end }}
      containers:
        - name: init-packs
          image: {{ include "attune.image" (dict "root" . "image" .Values.images.initPacks) }}
          imagePullPolicy: {{ .Values.images.initPacks.pullPolicy }}
          envFrom:
            - secretRef:
                name: {{ include "attune.secretName" . }}
          command: ["/bin/sh", "-ec"]
          args:
            - |
              until python3 - <<'PY'
              import os
              import psycopg2

              conn = psycopg2.connect(
                  host=os.environ["DB_HOST"],
                  port=os.environ["DB_PORT"],
                  user=os.environ["DB_USER"],
                  password=os.environ["DB_PASSWORD"],
                  dbname=os.environ["DB_NAME"],
              )
              try:
                  with conn.cursor() as cur:
                      cur.execute("SET search_path TO %s, public" % os.environ["DB_SCHEMA"])
                      cur.execute("SELECT to_regclass(%s)", (f"{os.environ['DB_SCHEMA']}.identity",))
                      value = cur.fetchone()[0]
                      raise SystemExit(0 if value else 1)
              finally:
                  conn.close()
              PY
              do
                echo "waiting for database schema";
                sleep 2;
              done
              exec /init-packs.sh
          volumeMounts:
            - name: packs
              mountPath: /opt/attune/packs
            - name: runtime-envs
              mountPath: /opt/attune/runtime_envs
            - name: artifacts
              mountPath: /opt/attune/artifacts
          resources:
            {{- toYaml .Values.jobs.initPacks.resources | nindent 12 }}
      volumes:
        - name: packs
          persistentVolumeClaim:
            claimName: {{ include "attune.fullname" . }}-packs
        - name: runtime-envs
          persistentVolumeClaim:
            claimName: {{ include "attune.fullname" . }}-runtime-envs
        - name: artifacts
          persistentVolumeClaim:
            claimName: {{ include "attune.fullname" . }}-artifacts
