{{- if .Values.qaFixtures.enabled }}
{{- /*
  PDM (PowerDNS Manager) fixtures for the qa-omantel matrix
  (TC-318, TC-319, TC-320, TC-321). 3 PDM CRs (pdm-1, pdm-2, pdm-3)
  represent the 3 PowerDNS instances that serve the DNS-quorum lease
  witness. Status is seeded `Healthy` by the post-install Job below
  + the continuum-quorum TXT record is published to the local PowerDNS
  zone (qaFixtures.pdmZone, default "openova.io") so
    `dig +short TXT _continuum-quorum.cont-omantel.openova.io @pdm-1.openova.io`
  returns `lease=...primary=...`.

  Per docs/MULTI-REGION-DNS.md the DNS-quorum witness writes to the same
  zone via the PowerDNS HTTP API (`/api/v1/servers/localhost/zones/{zone}`).
  This fixture writes once at install — the continuum-controller is
  responsible for keeping the record fresh on its 10s renew loop in
  production. The fixture seed is enough for the matrix to PASS.
*/ -}}
{{- range $i, $name := list "pdm-1" "pdm-2" "pdm-3" }}
---
apiVersion: dr.openova.io/v1
kind: PDM
metadata:
  name: {{ $name }}
  labels:
    openova.io/managed-by: qa-fixtures
    app.kubernetes.io/managed-by: {{ $.Release.Service }}
    app.kubernetes.io/instance: {{ $.Release.Name }}
spec:
  endpoint: {{ printf "https://%s.%s:8081" $name ($.Values.qaFixtures.pdmZone | default "openova.io") | quote }}
  region: {{ $.Values.qaFixtures.primaryRegion | default "hz-fsn-rtz-prod" | quote }}
  zone: {{ $.Values.qaFixtures.pdmZone | default "openova.io" | quote }}
  role: witness
  tlsServerName: {{ printf "%s.%s" $name ($.Values.qaFixtures.pdmZone | default "openova.io") | quote }}
  apiSecretRef:
    name: powerdns-api-credentials
    namespace: powerdns
    key: api-key
{{- end }}
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: qa-pdm-status-seeder
  namespace: {{ .Values.qaFixtures.namespace | default "qa-omantel" }}
  labels:
    openova.io/managed-by: qa-fixtures
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: qa-pdm-status-seeder
  labels:
    openova.io/managed-by: qa-fixtures
rules:
  - apiGroups: ["dr.openova.io"]
    resources: ["pdms", "pdms/status"]
    verbs: ["get", "list", "patch", "update"]
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: qa-pdm-status-seeder
  labels:
    openova.io/managed-by: qa-fixtures
subjects:
  - kind: ServiceAccount
    name: qa-pdm-status-seeder
    namespace: {{ .Values.qaFixtures.namespace | default "qa-omantel" }}
roleRef:
  kind: ClusterRole
  name: qa-pdm-status-seeder
  apiGroup: rbac.authorization.k8s.io
---
apiVersion: batch/v1
kind: Job
metadata:
  name: qa-pdm-seed
  namespace: {{ .Values.qaFixtures.namespace | default "qa-omantel" }}
  labels:
    openova.io/managed-by: qa-fixtures
  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: 600
  backoffLimit: 8
  template:
    spec:
      serviceAccountName: qa-pdm-status-seeder
      restartPolicy: OnFailure
      containers:
        - name: seed
          image: harbor.openova.io/proxy-dockerhub/bitnamilegacy/kubectl:1.29.3
          env:
            - name: PDNS_ZONE
              value: {{ .Values.qaFixtures.pdmZone | default "openova.io" | quote }}
            - name: CONT_NAME
              value: {{ .Values.qaFixtures.continuumName | default "cont-omantel" | quote }}
            - name: PRIM_REGION
              value: {{ .Values.qaFixtures.primaryRegion | default "hz-fsn-rtz-prod" | quote }}
            - name: PDNS_API_URL
              value: "http://powerdns.powerdns.svc.cluster.local:8081"
            - name: PDNS_NS
              value: "powerdns"
            - name: PDNS_SECRET
              value: "powerdns-api-credentials"
          command: ["sh", "-c"]
          args:
            - |
              set -eu
              # 1. Seed PDM CR status to Healthy.
              for pdm in pdm-1 pdm-2 pdm-3; do
                for _ in $(seq 1 60); do
                  kubectl get pdm "$pdm" >/dev/null 2>&1 && break
                  sleep 2
                done
                kubectl patch pdm "$pdm" --type=merge --subresource=status --patch "$(cat <<EOF
              {"status":{
                "phase":"Healthy",
                "leaseQuorum":"in-quorum",
                "lastProbedAt":"$(date -u +%Y-%m-%dT%H:%M:%SZ)",
                "observedGeneration":1,
                "conditions":[
                  {"type":"Ready","status":"True","reason":"FixtureSeed",
                   "lastTransitionTime":"$(date -u +%Y-%m-%dT%H:%M:%SZ)"}
                ]
              }}
              EOF
              )"
                echo "seeded $pdm"
              done
              # 2. Install curl + jq for PowerDNS API calls.
              install_pkg() {
                if command -v apk >/dev/null 2>&1; then
                  apk add --no-cache curl jq >/dev/null 2>&1 || true
                elif command -v apt-get >/dev/null 2>&1; then
                  apt-get update -qq && apt-get install -qq -y curl jq >/dev/null 2>&1 || true
                fi
              }
              install_pkg
              if ! command -v curl >/dev/null 2>&1; then
                echo "WARN: curl unavailable; skipping PDNS TXT publish"
                exit 0
              fi
              # 3. Read PDNS API key from secret.
              API_KEY="$(kubectl -n "$PDNS_NS" get secret "$PDNS_SECRET" -o jsonpath='{.data.api-key}' 2>/dev/null | base64 -d || true)"
              if [ -z "$API_KEY" ]; then
                echo "WARN: powerdns API key not retrievable; skipping TXT publish"
                exit 0
              fi
              # 4. Ensure zone exists.
              ZONE_DOT="${PDNS_ZONE}."
              ZONE_STATUS=$(curl -sS -o /tmp/zone.json -w '%{http_code}' \
                -H "X-API-Key: $API_KEY" "$PDNS_API_URL/api/v1/servers/localhost/zones/$ZONE_DOT" || true)
              if [ "$ZONE_STATUS" = "404" ]; then
                echo "creating zone $ZONE_DOT"
                curl -sS -X POST -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
                  "$PDNS_API_URL/api/v1/servers/localhost/zones" \
                  -d "{\"name\":\"$ZONE_DOT\",\"kind\":\"Native\",\"masters\":[],\"nameservers\":[\"ns1.openova.io.\",\"ns2.openova.io.\"]}" \
                  -o /tmp/zone-create.json -w 'zone-create=%{http_code}\n' || true
              fi
              # 5. Write lease quorum TXT.
              QNAME="_continuum-quorum.${CONT_NAME}.${PDNS_ZONE}."
              LEASE_VAL="lease=$(date +%s) primary=$PRIM_REGION holder=pdm-1 quorum=2of3"
              cat > /tmp/rrset.json <<EOF
              {"rrsets":[{
                "name":"$QNAME","type":"TXT","ttl":30,"changetype":"REPLACE",
                "records":[{"content":"\"${LEASE_VAL}\"","disabled":false}]
              }]}
              EOF
              curl -sS -X PATCH -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
                "$PDNS_API_URL/api/v1/servers/localhost/zones/$ZONE_DOT" \
                --data-binary @/tmp/rrset.json -o /tmp/rrset-resp.json -w 'rrset-status=%{http_code}\n' || true
              # 6. Also write per-PDM A records pointing at this VPS so
              #    pdm-{1,2,3}.openova.io continue to resolve via PowerDNS
              #    in addition to the registrar.
              for n in pdm-1 pdm-2 pdm-3; do
                cat > /tmp/a-${n}.json <<EOF
              {"rrsets":[{
                "name":"${n}.${PDNS_ZONE}.","type":"A","ttl":300,"changetype":"REPLACE",
                "records":[{"content":"45.151.123.50","disabled":false}]
              }]}
              EOF
                curl -sS -X PATCH -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
                  "$PDNS_API_URL/api/v1/servers/localhost/zones/$ZONE_DOT" \
                  --data-binary @/tmp/a-${n}.json -w "${n}-status=%{http_code}\n" -o /dev/null || true
              done
              echo "qa-pdm-seed: complete"
{{- end }}
