apiVersion: batch/v1
kind: Job
metadata:
  name: "${name}-dash-install-manifests"
spec:
  template:
    spec:
      serviceAccountName: $serviceAccount
      restartPolicy: Never
      containers:
      - name: init
        image: $imageK8sDeployToolsFull
        command: ["/bin/sh", "-c"]
        args:
          - |
            # fail at first command that fails
            set -e


            # create oidc and sentry secrets
            kubectl create secret generic dashboard-oidc || true
            kubectl create secret generic dashboard-sentry || true


            # wait for needed CRDs to exist and be ready; timeout of 30s
            # those CRDs are installed by stack installer
            # wait for presslabs-system namespace to exists
            RESOURCES="certificates.cert-manager.io issuers.cert-manager.io"
            i=0
            while [ $i -lt 30  ]; do
              i=$(expr $i + 1)
              kubectl get crd $RESOURCES \
                && kubectl get namespace presslabs-system \
                && kubectl get application ${name} -n ${namespace} \
                && kubectl -n presslabs-system get deployment/stack-cm-cert-manager-webhook \
                && i=30
              sleep 1
            done

            # expect CRDs to be ready
            kubectl wait --for condition=established crd $RESOURCES --timeout=120s

            # wait for cert-manager webhook to be ready
            kubectl wait --namespace presslabs-system --for condition=Available deployment/stack-cm-cert-manager-webhook --timeout=120s


            # patch with application UID and create resources
            # don't validate due to: https://github.com/jetstack/cert-manager/issues/1143
            export APP_UID=$(kubectl get applications.app.k8s.io ${name} -o jsonpath --template '{.metadata.uid}');
            echo -e "\n++ Patching resources with owner reference: $name ($APP_UID)\n" ;


            setOwnerReference() {
              kubectl patch $@ --type='json' -p="[{\"op\": \"add\", \"path\": \"/metadata/ownerReferences\", \"value\": [{\"apiVersion\": \"apps.k8s.io/v1beta1\", \"kind\": \"application\", \"name\": \"${name}\", \"uid\": \"$APP_UID\"}]}]"
            }

            setOwnerReference secret dashboard-oidc
            setOwnerReference secret dashboard-sentry


            cat /data/globals/manifest_globals.yaml | env -i "APPLICATION_UID=$APP_UID" envsubst | kubectl apply -f- --validate=false ;

        volumeMounts:
        - name: globals-manifests
          mountPath: /data/globals/
      volumes:
      - name: globals-manifests
        configMap:
          name: "${name}-dash-globals-manifests"

  backoffLimit: 3
