# services/veles/oneoffs/veles-secrets-ensure-job.yaml
# One-off job for veles/veles-secrets-ensure-2.
# Purpose: seed Veles Vault paths before app/Postgres pods are scaled up.
# Keep suspended until the veles Vault role has reconciled, then unsuspend once.
apiVersion: batch/v1
kind: Job
metadata:
  name: veles-secrets-ensure-2
  namespace: veles
spec:
  suspend: true
  backoffLimit: 0
  ttlSecondsAfterFinished: 3600
  template:
    spec:
      serviceAccountName: veles-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: bitnami/kubectl@sha256:554ab88b1858e8424c55de37ad417b16f2a0e65d1607aa0f3fe3ce9b9f10b131
          command: ["/bin/bash", "-c"]
          args:
            - |
              set -euo pipefail

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

              read_secret() {
                path="$1"
                out="$2"
                curl -sS -o "${out}" -w "%{http_code}" \
                  -H "X-Vault-Token: ${vault_token}" \
                  "${vault_addr}/v1/kv/data/atlas/${path}" || true
              }

              write_secret() {
                path="$1"
                payload="$2"
                out="$(mktemp)"
                status="$(curl -sS -o "${out}" -w "%{http_code}" -X POST \
                  -H "X-Vault-Token: ${vault_token}" \
                  -H "Content-Type: application/json" \
                  -d "${payload}" \
                  "${vault_addr}/v1/kv/data/atlas/${path}")"
                if [ "${status}" != "200" ] && [ "${status}" != "204" ]; then
                  echo "Vault write failed for ${path} (status ${status})" >&2
                  cat "${out}" >&2 || true
                  exit 1
                fi
              }

              rand_b64() {
                bytes="$1"
                openssl rand -base64 "${bytes}" | tr -d '\n'
              }

              status="$(read_secret veles/veles-db /tmp/veles-db.json)"
              if [ "${status}" = "200" ]; then
                db_password="$(jq -r '.data.data.POSTGRES_PASSWORD // empty' /tmp/veles-db.json)"
              elif [ "${status}" = "404" ]; then
                db_password=""
              else
                echo "Vault read failed for veles-db (status ${status})" >&2
                cat /tmp/veles-db.json >&2 || true
                exit 1
              fi
              if [ -z "${db_password}" ]; then
                db_password="$(rand_b64 36)"
              fi
              db_payload="$(jq -nc \
                --arg host "veles-postgres.veles.svc.cluster.local" \
                --arg port "5432" \
                --arg db "veles" \
                --arg user "veles" \
                --arg password "${db_password}" \
                '{data:{POSTGRES_HOST:$host,POSTGRES_PORT:$port,POSTGRES_DB:$db,POSTGRES_USER:$user,POSTGRES_PASSWORD:$password,DATABASE_URL:("postgresql://"+($user|@uri)+":"+($password|@uri)+"@"+$host+":"+$port+"/"+($db|@uri)+"?sslmode=disable")}}')"
              write_secret veles/veles-db "${db_payload}"

              status="$(read_secret veles/app-secrets /tmp/app-secrets.json)"
              if [ "${status}" = "200" ]; then
                session_secret="$(jq -r '.data.data.VELES_SESSION_SECRET // empty' /tmp/app-secrets.json)"
                byok_key="$(jq -r '.data.data.VELES_BYOK_ENCRYPTION_KEY // empty' /tmp/app-secrets.json)"
              elif [ "${status}" = "404" ]; then
                session_secret=""
                byok_key=""
              else
                echo "Vault read failed for app-secrets (status ${status})" >&2
                cat /tmp/app-secrets.json >&2 || true
                exit 1
              fi
              if [ -z "${session_secret}" ]; then
                session_secret="$(rand_b64 48)"
              fi
              if [ -z "${byok_key}" ]; then
                byok_key="$(rand_b64 32)"
              fi
              app_payload="$(jq -nc \
                --arg session_secret "${session_secret}" \
                --arg byok_key "${byok_key}" \
                '{data:{VELES_SESSION_SECRET:$session_secret,VELES_BYOK_ENCRYPTION_KEY:$byok_key}}')"
              write_secret veles/app-secrets "${app_payload}"

              postmark_status="$(read_secret shared/postmark-relay /tmp/postmark.json)"
              if [ "${postmark_status}" = "200" ]; then
                smtp_password="$(jq -r '.data.data.apikey // empty' /tmp/postmark.json)"
                if [ -n "${smtp_password}" ]; then
                  smtp_payload="$(jq -nc \
                    --arg host "mail.bstein.dev" \
                    --arg port "587" \
                    --arg user "${smtp_password}" \
                    --arg password "${smtp_password}" \
                    --arg from "no-reply-veles@bstein.dev" \
                    --arg from_name "Veles" \
                    '{data:{SMTP_HOST:$host,SMTP_PORT:$port,SMTP_USER:$user,SMTP_PASSWORD:$password,SMTP_FROM:$from,SMTP_FROM_NAME:$from_name,SMTP_STARTTLS:"true"}}')"
                  write_secret veles/smtp "${smtp_payload}"
                fi
              fi

              echo "Veles Vault paths ready: veles-db, app-secrets, smtp when Postmark relay exists"
