#@ load("@ytt:data", "data")

#@ ns = data.values.application.namespace

#@ secrets = []
#@ if data.values.ocis.s3.external:
#@   secrets.append("ocis-s3-credentials")
#@ end
#@ if data.values.backups.enabled and data.values.backups.storagebox.enabled:
#@   secrets.append("ocis-storagebox-credentials")
#@ end

#@ if len(secrets) > 0:
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: ocis-external-secret-precheck
  namespace: #@ ns
  annotations:
    argocd.argoproj.io/hook: PreSync
    argocd.argoproj.io/sync-wave: "-2"

---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: ocis-external-secret-precheck
  namespace: #@ ns
  annotations:
    argocd.argoproj.io/hook: PreSync
    argocd.argoproj.io/sync-wave: "-2"
rules:
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get"]

---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: ocis-external-secret-precheck
  namespace: #@ ns
  annotations:
    argocd.argoproj.io/hook: PreSync
    argocd.argoproj.io/sync-wave: "-2"
subjects:
  - kind: ServiceAccount
    name: ocis-external-secret-precheck
    namespace: #@ ns
roleRef:
  kind: Role
  name: ocis-external-secret-precheck
  apiGroup: rbac.authorization.k8s.io

---
apiVersion: batch/v1
kind: Job
metadata:
  name: ocis-external-secret-precheck
  namespace: #@ ns
  annotations:
    argocd.argoproj.io/hook: PreSync
    argocd.argoproj.io/sync-wave: "-1"
    argocd.argoproj.io/sync-options: Replace=true
spec:
  ttlSecondsAfterFinished: 300
  template:
    spec:
      serviceAccountName: ocis-external-secret-precheck
      restartPolicy: OnFailure
      securityContext:
        runAsNonRoot: true
        runAsUser: 65532
        runAsGroup: 65532
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: precheck
          image: alpine/k8s:1.32.3
          command:
            - sh
            - -c
            - #@ "set -e\nfor s in " + " ".join(secrets) + "; do\n  if ! kubectl get secret \"$s\" -n \"${NAMESPACE}\" >/dev/null 2>&1; then\n    echo \"ERROR: External secret $s must be created manually before deploying ocis\"\n    exit 1\n  fi\n  echo \"OK: $s exists\"\ndone\n"
          env:
            - name: NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop:
              - ALL
#@ end
