# services/keycloak/oneoffs/mas-secrets-ensure-job.yaml
# One-off job for sso/mas-secrets-ensure.
# Purpose: mas secrets ensure (see container args/env in this file).
# Run by setting spec.suspend to false, reconcile, then set it back to true.
# Safe to delete the finished Job/pod; it should not run continuously.
apiVersion: v1
kind: ServiceAccount
metadata:
  name: mas-secrets-ensure
  namespace: sso
imagePullSecrets:
  - name: harbor-regcred
---
apiVersion: batch/v1
kind: Job
metadata:
  name: mas-secrets-ensure-21
  namespace: sso
spec:
  suspend: true
  backoffLimit: 0
  ttlSecondsAfterFinished: 3600
  template:
    metadata:
      annotations:
        vault.hashicorp.com/agent-inject: "true"
        vault.hashicorp.com/agent-pre-populate-only: "true"
        vault.hashicorp.com/agent-init-first: "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 }}"
          export KEYCLOAK_ADMIN_USER="{{ .Data.data.username }}"
          export KEYCLOAK_ADMIN_PASSWORD="{{ .Data.data.password }}"
          {{ end }}
    spec:
      serviceAccountName: mas-secrets-ensure
      restartPolicy: Never
      nodeSelector:
        kubernetes.io/arch: arm64
        node-role.kubernetes.io/worker: "true"
      volumes:
        - name: work
          emptyDir: {}
      initContainers:
        - name: generate
          image: bitnami/kubectl@sha256:554ab88b1858e8424c55de37ad417b16f2a0e65d1607aa0f3fe3ce9b9f10b131
          command: ["/bin/sh", "-c"]
          args:
            - |
              set -euo pipefail
              . /vault/secrets/keycloak-admin-env.sh
              umask 077

              KC_URL="http://keycloak.sso.svc.cluster.local"
              for attempt in 1 2 3 4 5 6 7 8 9 10; do
                if curl -fsS "${KC_URL}/realms/master" >/dev/null 2>&1; then
                  break
                fi
                echo "Waiting for Keycloak to be reachable (attempt ${attempt})" >&2
                sleep $((attempt * 2))
              done
              ACCESS_TOKEN=""
              for attempt in 1 2 3 4 5; do
                TOKEN_JSON="$(curl -sS -X POST "$KC_URL/realms/master/protocol/openid-connect/token" \
                  -H 'Content-Type: application/x-www-form-urlencoded' \
                  -d "grant_type=password" \
                  -d "client_id=admin-cli" \
                  -d "username=${KEYCLOAK_ADMIN}" \
                  -d "password=${KEYCLOAK_ADMIN_PASSWORD}" || true)"
                ACCESS_TOKEN="$(echo "$TOKEN_JSON" | jq -r '.access_token' 2>/dev/null || true)"
                if [ -n "$ACCESS_TOKEN" ] && [ "$ACCESS_TOKEN" != "null" ]; then
                  break
                fi
                echo "Keycloak token request failed (attempt ${attempt})" >&2
                sleep $((attempt * 2))
              done
              if [ -z "$ACCESS_TOKEN" ] || [ "$ACCESS_TOKEN" = "null" ]; then
                echo "Failed to fetch Keycloak admin token" >&2
                exit 1
              fi
              CLIENT_ID=""
              for attempt in 1 2 3 4 5; do
                CLIENT_QUERY="$(curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" \
                  "$KC_URL/admin/realms/atlas/clients?clientId=othrys-mas" || true)"
                CLIENT_ID="$(echo "$CLIENT_QUERY" | jq -r '.[0].id' 2>/dev/null || true)"
                if [ -n "$CLIENT_ID" ] && [ "$CLIENT_ID" != "null" ]; then
                  break
                fi
                echo "Keycloak client lookup failed (attempt ${attempt})" >&2
                sleep $((attempt * 2))
              done
              if [ -z "$CLIENT_ID" ] || [ "$CLIENT_ID" = "null" ]; then
                echo "Keycloak client othrys-mas not found" >&2
                exit 1
              fi
              CLIENT_SECRET=""
              for attempt in 1 2 3 4 5; do
                CLIENT_SECRET="$(curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" \
                  "$KC_URL/admin/realms/atlas/clients/${CLIENT_ID}/client-secret" | jq -r '.value' 2>/dev/null || true)"
                if [ -n "$CLIENT_SECRET" ] && [ "$CLIENT_SECRET" != "null" ]; then
                  break
                fi
                echo "Keycloak client secret lookup failed (attempt ${attempt})" >&2
                sleep $((attempt * 2))
              done
              if [ -z "$CLIENT_SECRET" ] || [ "$CLIENT_SECRET" = "null" ]; then
                echo "Keycloak client secret not found" >&2
                exit 1
              fi

              printf '%s' "$CLIENT_SECRET" > /work/keycloak_client_secret
              openssl rand -hex 32 | tr -d '\n' > /work/encryption
              openssl rand -hex 32 | tr -d '\n' > /work/matrix_shared_secret
              openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:4096 -out /work/rsa_key >/dev/null 2>&1
              chmod 0644 /work/*
          volumeMounts:
            - name: work
              mountPath: /work
      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}"
              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

              existing="$(curl -sS -H "X-Vault-Token: ${vault_token}" \
                "${vault_addr}/v1/kv/data/atlas/comms/mas-secrets-runtime" | jq -r '.data.data.encryption // empty')"
              if [ -n "${existing}" ]; then
                current_len="$(printf '%s' "${existing}" | wc -c | tr -d ' ')"
                if [ "${current_len}" = "64" ] && printf '%s' "${existing}" | grep -Eq '^[0-9a-fA-F]{64}$'; then
                  exit 0
                fi
              fi

              payload="$(jq -nc \
                --arg encryption "$(cat /work/encryption)" \
                --arg matrix_shared_secret "$(cat /work/matrix_shared_secret)" \
                --arg keycloak_client_secret "$(cat /work/keycloak_client_secret)" \
                --arg rsa_key "$(cat /work/rsa_key)" \
                '{data:{encryption:$encryption, matrix_shared_secret:$matrix_shared_secret, keycloak_client_secret:$keycloak_client_secret, rsa_key:$rsa_key}}')"
              curl -sS -X POST -H "X-Vault-Token: ${vault_token}" \
                -d "${payload}" "${vault_addr}/v1/kv/data/atlas/comms/mas-secrets-runtime" >/dev/null
          volumeMounts:
            - name: work
              mountPath: /work
