#!/usr/bin/env sh
set -euo pipefail

. /vault/secrets/keycloak-admin-env.sh

KC_URL="http://keycloak.sso.svc.cluster.local"
ACCESS_TOKEN=""
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
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_QUERY="$(curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  "$KC_URL/admin/realms/atlas/clients?clientId=actual-budget" || true)"
CLIENT_ID="$(echo "$CLIENT_QUERY" | jq -r '.[0].id' 2>/dev/null || true)"

if [ -z "$CLIENT_ID" ] || [ "$CLIENT_ID" = "null" ]; then
  create_payload='{"clientId":"actual-budget","enabled":true,"protocol":"openid-connect","publicClient":false,"standardFlowEnabled":true,"implicitFlowEnabled":false,"directAccessGrantsEnabled":false,"serviceAccountsEnabled":false,"redirectUris":["https://budget.bstein.dev/openid/callback"],"webOrigins":["https://budget.bstein.dev"],"rootUrl":"https://budget.bstein.dev","baseUrl":"/"}'
  status="$(curl -sS -o /dev/null -w "%{http_code}" -X POST \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    -H 'Content-Type: application/json' \
    -d "${create_payload}" \
    "$KC_URL/admin/realms/atlas/clients")"
  if [ "$status" != "201" ] && [ "$status" != "204" ] && [ "$status" != "409" ]; then
    echo "Keycloak client create failed (status ${status})" >&2
    exit 1
  fi
  CLIENT_QUERY="$(curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    "$KC_URL/admin/realms/atlas/clients?clientId=actual-budget" || true)"
  CLIENT_ID="$(echo "$CLIENT_QUERY" | jq -r '.[0].id' 2>/dev/null || true)"
fi

if [ -z "$CLIENT_ID" ] || [ "$CLIENT_ID" = "null" ]; then
  echo "Keycloak client actual-budget not found" >&2
  exit 1
fi

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 [ -z "$CLIENT_SECRET" ] || [ "$CLIENT_SECRET" = "null" ]; then
  echo "Keycloak client secret not found" >&2
  exit 1
fi

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

payload="$(jq -nc \
  --arg client_id "actual-budget" \
  --arg client_secret "${CLIENT_SECRET}" \
  '{data:{ACTUAL_OPENID_CLIENT_ID:$client_id, ACTUAL_OPENID_CLIENT_SECRET:$client_secret}}')"

curl -sS -X POST -H "X-Vault-Token: ${vault_token}" \
  -d "${payload}" "${vault_addr}/v1/kv/data/atlas/finance/actual-oidc" >/dev/null
