# services/comms/bootstrap-jobs/mas-db-ensure-job.yaml
# One-off job for comms/mas-db-ensure-22.
# Purpose: mas db ensure 22 (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: mas-db-ensure-22
  namespace: comms
spec:
  suspend: true
  backoffLimit: 1
  ttlSecondsAfterFinished: 600
  template:
    spec:
      serviceAccountName: mas-db-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 "mas-db-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() {
                curl -sS -H "X-Vault-Token: ${vault_token}" \
                  "${vault_addr}/v1/kv/data/atlas/comms/mas-db" | jq -r '.data.data.password // empty'
              }

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

              MAS_PASS="$(vault_read)"
              if [ -z "${MAS_PASS}" ] || printf '%s' "${MAS_PASS}" | grep -Eq '[^A-Za-z0-9_-]'; then
                MAS_PASS="$(safe_pass)"
                vault_write "${MAS_PASS}"
              fi

              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

              MAS_PASS_SQL="$(printf '%s' "${MAS_PASS}" | sed "s/'/''/g")"
              kubectl -n postgres exec -i "${POD_NAME}" -- psql -U postgres -d postgres \
                -c "CREATE ROLE mas LOGIN PASSWORD '${MAS_PASS_SQL}';" || true
              kubectl -n postgres exec -i "${POD_NAME}" -- psql -U postgres -d postgres \
                -c "ALTER ROLE mas WITH PASSWORD '${MAS_PASS_SQL}';"
              kubectl -n postgres exec -i "${POD_NAME}" -- psql -U postgres -d postgres \
                -c "CREATE DATABASE mas OWNER mas;" || true
              kubectl -n postgres exec -i "${POD_NAME}" -- /bin/sh -c \
                "PGPASSWORD='${MAS_PASS_SQL}' psql -U mas -d mas -c 'select 1;'"
