# services/comms/bootstrap-jobs/comms-secrets-ensure-job.yaml
# One-off job for comms/comms-secrets-ensure-7.
# Purpose: comms secrets ensure 7 (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: batch/v1
kind: Job
metadata:
  name: comms-secrets-ensure-7
  namespace: comms
spec:
  suspend: true
  backoffLimit: 1
  ttlSecondsAfterFinished: 3600
  template:
    spec:
      serviceAccountName: comms-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: ensure
          image: registry.bstein.dev/bstein/kubectl:1.35.0
          command: ["/bin/sh", "-c"]
          args:
            - |
              set -eu
              trap 'echo "comms-secrets-ensure failed"; sleep 300' ERR
              umask 077

              safe_pass() {
                head -c 32 /dev/urandom | base64 | tr -d '\n' | tr '+/' '-_' | tr -d '='
              }

              vault_addr="${VAULT_ADDR:-http://vault.vault.svc.cluster.local:8200}"
              vault_role="${VAULT_ROLE:-comms-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

              vault_read() {
                path="$1"
                key="$2"
                curl -sS -H "X-Vault-Token: ${vault_token}" \
                  "${vault_addr}/v1/kv/data/atlas/${path}" | jq -r --arg key "${key}" '.data.data[$key] // empty'
              }

              vault_write() {
                path="$1"
                key="$2"
                value="$3"
                payload="$(jq -nc --arg key "${key}" --arg value "${value}" '{data:{($key):$value}}')"
                curl -sS -X POST -H "X-Vault-Token: ${vault_token}" \
                  -d "${payload}" "${vault_addr}/v1/kv/data/atlas/${path}" >/dev/null
              }

              ensure_key() {
                path="$1"
                key="$2"
                current="$(vault_read "${path}" "${key}")"
                if [ -z "${current}" ]; then
                  current="$(safe_pass)"
                  vault_write "${path}" "${key}" "${current}"
                fi
                printf '%s' "${current}"
              }

              ensure_key "comms/turn-shared-secret" "TURN_STATIC_AUTH_SECRET" >/dev/null
              ensure_key "comms/livekit-api" "primary" >/dev/null
              ensure_key "comms/synapse-redis" "redis-password" >/dev/null
              ensure_key "comms/synapse-macaroon" "macaroon_secret_key" >/dev/null
              ensure_key "comms/atlasbot-credentials-runtime" "bot-password" >/dev/null
              ensure_key "comms/atlasbot-credentials-runtime" "seeder-password" >/dev/null

              SYN_PASS="$(ensure_key "comms/synapse-db" "POSTGRES_PASSWORD")"

              POD_NAME="$(kubectl -n postgres get pods -l app=postgres -o jsonpath='{.items[0].metadata.name}')"
              if [ -z "${POD_NAME}" ]; then
                echo "postgres pod not found" >&2
                exit 1
              fi
              SYN_PASS_SQL="$(printf '%s' "${SYN_PASS}" | sed "s/'/''/g")"
              kubectl -n postgres exec -i "${POD_NAME}" -- psql -U postgres -d postgres \
                -c "CREATE ROLE synapse LOGIN PASSWORD '${SYN_PASS_SQL}';" || true
              kubectl -n postgres exec -i "${POD_NAME}" -- psql -U postgres -d postgres \
                -c "ALTER ROLE synapse WITH PASSWORD '${SYN_PASS_SQL}';"
              kubectl -n postgres exec -i "${POD_NAME}" -- psql -U postgres -d postgres \
                -c "CREATE DATABASE synapse OWNER synapse;" || true
