# services/keycloak/bootstrap-jobs/metis-ssh-keys-secret-ensure-job.yaml
# One-off job for sso/metis-ssh-keys-secret-ensure-1.
# Purpose: ensure Vault path maintenance/metis-ssh-keys exists for Metis key injection.
# Migration behavior: if Vault path is missing/incomplete, seed from existing maintenance/metis-ssh-keys Kubernetes Secret.
# Legacy key names are read as fallback, but only ananke_* keys are written.
apiVersion: batch/v1
kind: Job
metadata:
  name: metis-ssh-keys-secret-ensure-1
  namespace: sso
spec:
  backoffLimit: 0
  ttlSecondsAfterFinished: 3600
  template:
    metadata:
      annotations:
        vault.hashicorp.com/agent-inject: "true"
        vault.hashicorp.com/agent-pre-populate-only: "true"
        vault.hashicorp.com/role: "sso-secrets"
        vault.hashicorp.com/agent-inject-secret-keycloak-admin-env.sh: "kv/data/atlas/shared/keycloak-admin"
        vault.hashicorp.com/agent-inject-template-keycloak-admin-env.sh: |
          {{ with secret "kv/data/atlas/shared/keycloak-admin" }}
          export KEYCLOAK_ADMIN="{{ .Data.data.username }}"
          {{ end }}
    spec:
      serviceAccountName: mas-secrets-ensure
      restartPolicy: Never
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
              - matchExpressions:
                  - key: node-role.kubernetes.io/worker
                    operator: Exists
          preferredDuringSchedulingIgnoredDuringExecution:
            - weight: 100
              preference:
                matchExpressions:
                  - key: kubernetes.io/arch
                    operator: In
                    values: ["arm64"]
      containers:
        - name: apply
          image: registry.bstein.dev/bstein/kubectl:1.35.0
          command: ["/bin/sh", "-c"]
          args:
            - |
              set -euo pipefail

              vault_addr="${VAULT_ADDR:-http://vault.vault.svc.cluster.local:8200}"
              vault_role="${VAULT_ROLE:-sso-secrets}"
              vault_path="kv/data/atlas/maintenance/metis-ssh-keys"

              jwt="$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)"
              login_payload="$(jq -nc --arg jwt "${jwt}" --arg role "${vault_role}" '{jwt:$jwt, role:$role}')"
              vault_token="$(curl -sS --request POST --data "${login_payload}" \
                "${vault_addr}/v1/auth/kubernetes/login" | jq -r '.auth.client_token')"
              if [ -z "${vault_token}" ] || [ "${vault_token}" = "null" ]; then
                echo "vault login failed" >&2
                exit 1
              fi

              read_status="$(curl -sS -o /tmp/metis-ssh-read.json -w "%{http_code}" \
                -H "X-Vault-Token: ${vault_token}" \
                "${vault_addr}/v1/${vault_path}" || true)"
              if [ "${read_status}" = "200" ]; then
                bastion_existing="$(jq -r '.data.data.bastion_pub // empty' /tmp/metis-ssh-read.json)"
                brad_existing="$(jq -r '.data.data.brad_pub // empty' /tmp/metis-ssh-read.json)"
                ananke_tethys_existing="$(jq -r '.data.data.ananke_tethys_pub // .data.data.hecate_tethys_pub // empty' /tmp/metis-ssh-read.json)"
                ananke_db_existing="$(jq -r '.data.data.ananke_db_pub // .data.data.hecate_db_pub // empty' /tmp/metis-ssh-read.json)"
                if [ -n "${bastion_existing}" ] && [ -n "${brad_existing}" ] && [ -n "${ananke_tethys_existing}" ]; then
                  echo "Vault metis-ssh-keys already present"
                  exit 0
                fi
              elif [ "${read_status}" != "404" ]; then
                echo "Vault read failed (status ${read_status})" >&2
                cat /tmp/metis-ssh-read.json >&2 || true
                exit 1
              fi

              bastion_pub="$(kubectl -n maintenance get secret metis-ssh-keys -o jsonpath='{.data.bastion_pub}' 2>/dev/null | base64 -d || true)"
              brad_pub="$(kubectl -n maintenance get secret metis-ssh-keys -o jsonpath='{.data.brad_pub}' 2>/dev/null | base64 -d || true)"
              ananke_tethys_pub="$(kubectl -n maintenance get secret metis-ssh-keys -o jsonpath='{.data.ananke_tethys_pub}' 2>/dev/null | base64 -d || true)"
              if [ -z "${ananke_tethys_pub}" ]; then
                ananke_tethys_pub="$(kubectl -n maintenance get secret metis-ssh-keys -o jsonpath='{.data.hecate_tethys_pub}' 2>/dev/null | base64 -d || true)"
              fi
              ananke_db_pub="$(kubectl -n maintenance get secret metis-ssh-keys -o jsonpath='{.data.ananke_db_pub}' 2>/dev/null | base64 -d || true)"
              if [ -z "${ananke_db_pub}" ]; then
                ananke_db_pub="$(kubectl -n maintenance get secret metis-ssh-keys -o jsonpath='{.data.hecate_db_pub}' 2>/dev/null | base64 -d || true)"
              fi

              if [ -z "${bastion_pub}" ] && [ -n "${bastion_existing:-}" ]; then
                bastion_pub="${bastion_existing}"
              fi
              if [ -z "${brad_pub}" ] && [ -n "${brad_existing:-}" ]; then
                brad_pub="${brad_existing}"
              fi
              if [ -z "${ananke_tethys_pub}" ] && [ -n "${ananke_tethys_existing:-}" ]; then
                ananke_tethys_pub="${ananke_tethys_existing}"
              fi
              if [ -z "${ananke_db_pub}" ] && [ -n "${ananke_db_existing:-}" ]; then
                ananke_db_pub="${ananke_db_existing}"
              fi

              if [ -z "${bastion_pub}" ] || [ -z "${brad_pub}" ] || [ -z "${ananke_tethys_pub}" ]; then
                echo "Cannot seed Vault metis-ssh-keys: maintenance/metis-ssh-keys missing required keys" >&2
                exit 1
              fi

              payload="$(jq -nc \
                --arg bastion_pub "${bastion_pub}" \
                --arg brad_pub "${brad_pub}" \
                --arg ananke_tethys_pub "${ananke_tethys_pub}" \
                --arg ananke_db_pub "${ananke_db_pub}" \
                '{data:{bastion_pub:$bastion_pub,brad_pub:$brad_pub,ananke_tethys_pub:$ananke_tethys_pub,ananke_db_pub:$ananke_db_pub}}')"
              write_status="$(curl -sS -o /tmp/metis-ssh-write.json -w "%{http_code}" -X POST \
                -H "X-Vault-Token: ${vault_token}" \
                -H 'Content-Type: application/json' \
                -d "${payload}" \
                "${vault_addr}/v1/${vault_path}")"
              if [ "${write_status}" != "200" ] && [ "${write_status}" != "204" ]; then
                echo "Vault write failed (status ${write_status})" >&2
                cat /tmp/metis-ssh-write.json >&2 || true
                exit 1
              fi

              verify_status="$(curl -sS -o /tmp/metis-ssh-verify.json -w "%{http_code}" \
                -H "X-Vault-Token: ${vault_token}" \
                "${vault_addr}/v1/${vault_path}" || true)"
              if [ "${verify_status}" != "200" ]; then
                echo "Vault verify failed (status ${verify_status})" >&2
                cat /tmp/metis-ssh-verify.json >&2 || true
                exit 1
              fi

              echo "Metis SSH key material now persisted in Vault at maintenance/metis-ssh-keys"
