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

#@ ns = data.values.application.namespace

#@ if data.values.cluster.tls.issuer == "mkcert":
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: mkcert-ca-precheck
  namespace: #@ ns

---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: mkcert-ca-precheck
  namespace: #@ ns
rules:
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get"]

---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: mkcert-ca-precheck
  namespace: #@ ns
subjects:
  - kind: ServiceAccount
    name: mkcert-ca-precheck
    namespace: #@ ns
roleRef:
  kind: Role
  name: mkcert-ca-precheck
  apiGroup: rbac.authorization.k8s.io

---
apiVersion: batch/v1
kind: Job
metadata:
  name: mkcert-ca-precheck
  namespace: #@ ns
  annotations:
    argocd.argoproj.io/sync-wave: "-1"
    argocd.argoproj.io/sync-options: Replace=true
spec:
  ttlSecondsAfterFinished: 300
  template:
    spec:
      serviceAccountName: mkcert-ca-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
              if ! kubectl get secret mkcert-ca -n "${NAMESPACE}" >/dev/null 2>&1; then
                echo "ERROR: External secret mkcert-ca must be created in ${NAMESPACE} before deploying cert-manager."
                echo "Run: mkcert -install && kubectl -n ${NAMESPACE} create secret tls mkcert-ca --cert=\"\$(mkcert -CAROOT)/rootCA.pem\" --key=\"\$(mkcert -CAROOT)/rootCA-key.pem\""
                exit 1
              fi
              echo "OK: mkcert-ca exists"
          env:
            - name: NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop:
              - ALL
#@ end
