---
apiVersion: batch/v1
kind: Job
metadata:
  name: ${K8S_PROJECT}-restore-${BRANCH_HASH}
  labels:
    app: ${K8S_PROJECT}-restore-${BRANCH_HASH}
    git/branch: ${BRANCH_NAME}
    git/commit: ${COMMIT}
    gitlab/job: "${JOB_ID}"
spec:
  template:
    spec:
      containers:
        - name: ${K8S_PROJECT}-restore-${BRANCH_HASH}
          image: postgres:10-alpine
          command:
            - sh
          args:
            - -c
            - |
              sh -x /mnt/script/postgres-init.sh
              sh -x /mnt/script/restore.sh /mnt/data/$(cat /mnt/data/LATEST)
          resources:
            requests:
              cpu: 0m
              memory: 0Mi
            limits:
              cpu: 500m
              memory: 512Mi
          env:
            - name: PGUSER
              value: postgres
            - name: PGHOST
              value: ${K8S_PROJECT}-postgres-${BRANCH_HASH}
            - name: PGPASSWORD
              valueFrom:
                secretKeyRef:
                  name: ${K8S_PROJECT}-postgres-${BRANCH_HASH}
                  key: postgresql-password
            - name: POSTGRES_EMJPM_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: emjpm-secret
                  key: POSTGRES_EMJPM_PASSWORD
            - name: POSTGRES_HASURA_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: emjpm-secret
                  key: POSTGRES_HASURA_PASSWORD
            - name: POSTGRES_METABASE_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: emjpm-secret
                  key: POSTGRES_METABASE_PASSWORD
          volumeMounts:
            - mountPath: "/mnt/data"
              name: volume
            - mountPath: "/mnt/script"
              name: script
      restartPolicy: Never
      volumes:
        - name: script
          configMap:
            name: ${K8S_PROJECT}-restore-configmap-${BRANCH_HASH}
        - name: volume
          azureFile:
            secretName: ${K8S_PROJECT}-azure-storage-${BRANCH_HASH}
            shareName: emjpm-backup-restore
            readOnly: false
      initContainers:
        - name: wait-for-postgres
          image: postgres:10-alpine
          imagePullPolicy: Always
          resources:
            requests:
              cpu: 0m
              memory: 0Mi
            limits:
              cpu: 50m
              memory: 32Mi
          command:
            - sh
            - -c
            - |
              retry=120; # 5s * (12 * 10) = 10min
              while ! pg_isready -h ${POSTGRES_HOST} > /dev/null 2> /dev/null && [[ $(( retry-- )) -gt 0 ]];
                do
                  echo "Waiting for Postgres to go Green ($(( retry )))" ; sleep 5s ; done ;
              echo Ready;
