#!/usr/bin/env sh
set -eu

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

KC_URL="http://keycloak.sso.svc.cluster.local"
CHAT_CLIENT="hermes-chat-dashboard"
CHAT_URL="https://chat.bstein.dev"
OPERATOR_CLIENT="hermes-operator-proxy"
OPERATOR_URL="https://agent.bstein.dev"

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="$(printf '%s' "${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

chat_payload="$(jq -nc \
  --arg client_id "${CHAT_CLIENT}" \
  --arg redirect_uri "${CHAT_URL}/auth/callback" \
  --arg web_origin "${CHAT_URL}" \
  '{
    clientId:$client_id,
    enabled:true,
    protocol:"openid-connect",
    publicClient:true,
    standardFlowEnabled:true,
    implicitFlowEnabled:false,
    directAccessGrantsEnabled:false,
    serviceAccountsEnabled:false,
    redirectUris:[$redirect_uri],
    webOrigins:[$web_origin],
    rootUrl:$web_origin,
    baseUrl:"/",
    attributes:{
      "pkce.code.challenge.method":"S256",
      "post.logout.redirect.uris":$web_origin,
      "access.token.lifespan":"1200"
    }
  }')"

chat_query="$(curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  "${KC_URL}/admin/realms/atlas/clients?clientId=${CHAT_CLIENT}" || true)"
chat_id="$(printf '%s' "${chat_query}" | jq -r '.[0].id' 2>/dev/null || true)"
if [ -z "${chat_id}" ] || [ "${chat_id}" = "null" ]; then
  status="$(curl -sS -o /dev/null -w '%{http_code}' -X POST \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    -H 'Content-Type: application/json' \
    -d "${chat_payload}" \
    "${KC_URL}/admin/realms/atlas/clients")"
  if [ "${status}" != "201" ] && [ "${status}" != "204" ] && [ "${status}" != "409" ]; then
    echo "Keycloak chat client create failed (status ${status})" >&2
    exit 1
  fi
  chat_query="$(curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    "${KC_URL}/admin/realms/atlas/clients?clientId=${CHAT_CLIENT}" || true)"
  chat_id="$(printf '%s' "${chat_query}" | jq -r '.[0].id' 2>/dev/null || true)"
fi
if [ -z "${chat_id}" ] || [ "${chat_id}" = "null" ]; then
  echo "Keycloak chat client not found after create" >&2
  exit 1
fi

status="$(curl -sS -o /dev/null -w '%{http_code}' -X PUT \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H 'Content-Type: application/json' \
  -d "${chat_payload}" \
  "${KC_URL}/admin/realms/atlas/clients/${chat_id}")"
if [ "${status}" != "204" ]; then
  echo "Keycloak chat client update failed (status ${status})" >&2
  exit 1
fi

scope_id="$(curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  "${KC_URL}/admin/realms/atlas/client-scopes?search=groups" \
  | jq -r '.[] | select(.name=="groups") | .id' 2>/dev/null | head -n1 || true)"
if [ -z "${scope_id}" ] || [ "${scope_id}" = "null" ]; then
  echo "Keycloak groups client scope not found" >&2
  exit 1
fi
default_scopes="$(curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  "${KC_URL}/admin/realms/atlas/clients/${chat_id}/default-client-scopes" || true)"
optional_scopes="$(curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  "${KC_URL}/admin/realms/atlas/clients/${chat_id}/optional-client-scopes" || true)"
if ! printf '%s' "${default_scopes}" | jq -e '.[] | select(.name=="groups")' >/dev/null 2>&1 \
  && ! printf '%s' "${optional_scopes}" | jq -e '.[] | select(.name=="groups")' >/dev/null 2>&1; then
  status="$(curl -sS -o /dev/null -w '%{http_code}' -X PUT \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    "${KC_URL}/admin/realms/atlas/clients/${chat_id}/optional-client-scopes/${scope_id}")"
  if [ "${status}" != "200" ] && [ "${status}" != "201" ] && [ "${status}" != "204" ]; then
    status="$(curl -sS -o /dev/null -w '%{http_code}' -X POST \
      -H "Authorization: Bearer ${ACCESS_TOKEN}" \
      "${KC_URL}/admin/realms/atlas/clients/${chat_id}/optional-client-scopes/${scope_id}")"
    if [ "${status}" != "200" ] && [ "${status}" != "201" ] && [ "${status}" != "204" ]; then
      echo "Failed to attach groups scope to chat client (status ${status})" >&2
      exit 1
    fi
  fi
fi

operator_payload="$(jq -nc \
  --arg client_id "${OPERATOR_CLIENT}" \
  --arg redirect_uri "${OPERATOR_URL}/oauth2/callback" \
  --arg web_origin "${OPERATOR_URL}" \
  '{
    clientId:$client_id,
    enabled:true,
    protocol:"openid-connect",
    publicClient:false,
    standardFlowEnabled:true,
    implicitFlowEnabled:false,
    directAccessGrantsEnabled:false,
    serviceAccountsEnabled:false,
    redirectUris:[$redirect_uri],
    webOrigins:[$web_origin],
    rootUrl:$web_origin,
    baseUrl:"/",
    attributes:{"post.logout.redirect.uris":$web_origin}
  }')"

operator_query="$(curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  "${KC_URL}/admin/realms/atlas/clients?clientId=${OPERATOR_CLIENT}" || true)"
operator_id="$(printf '%s' "${operator_query}" | jq -r '.[0].id' 2>/dev/null || true)"
if [ -z "${operator_id}" ] || [ "${operator_id}" = "null" ]; then
  status="$(curl -sS -o /dev/null -w '%{http_code}' -X POST \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    -H 'Content-Type: application/json' \
    -d "${operator_payload}" \
    "${KC_URL}/admin/realms/atlas/clients")"
  if [ "${status}" != "201" ] && [ "${status}" != "204" ] && [ "${status}" != "409" ]; then
    echo "Keycloak operator proxy client create failed (status ${status})" >&2
    exit 1
  fi
  operator_query="$(curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    "${KC_URL}/admin/realms/atlas/clients?clientId=${OPERATOR_CLIENT}" || true)"
  operator_id="$(printf '%s' "${operator_query}" | jq -r '.[0].id' 2>/dev/null || true)"
fi
if [ -z "${operator_id}" ] || [ "${operator_id}" = "null" ]; then
  echo "Keycloak operator proxy client not found after create" >&2
  exit 1
fi

status="$(curl -sS -o /dev/null -w '%{http_code}' -X PUT \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H 'Content-Type: application/json' \
  -d "${operator_payload}" \
  "${KC_URL}/admin/realms/atlas/clients/${operator_id}")"
if [ "${status}" != "204" ]; then
  echo "Keycloak operator proxy client update failed (status ${status})" >&2
  exit 1
fi

client_secret="$(curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  "${KC_URL}/admin/realms/atlas/clients/${operator_id}/client-secret" \
  | jq -r '.value' 2>/dev/null || true)"
if [ -z "${client_secret}" ] || [ "${client_secret}" = "null" ]; then
  echo "Keycloak operator proxy 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

read_status="$(curl -sS -o /tmp/hermes-operator-oidc-read.json -w '%{http_code}' \
  -H "X-Vault-Token: ${vault_token}" \
  "${vault_addr}/v1/kv/data/atlas/hermes/operator-oidc" || true)"
cookie_secret=""
if [ "${read_status}" = "200" ]; then
  cookie_secret="$(jq -r '.data.data.cookie_secret // empty' /tmp/hermes-operator-oidc-read.json)"
elif [ "${read_status}" != "404" ]; then
  echo "Vault operator OIDC read failed (status ${read_status})" >&2
  exit 1
fi
if [ -n "${cookie_secret}" ]; then
  cookie_length="$(printf '%s' "${cookie_secret}" | wc -c | tr -d ' ')"
  if [ "${cookie_length}" != "16" ] && [ "${cookie_length}" != "24" ] && [ "${cookie_length}" != "32" ]; then
    cookie_secret=""
  fi
fi
if [ -z "${cookie_secret}" ]; then
  cookie_secret="$(openssl rand -hex 16 | tr -d '\n')"
fi

vault_payload="$(jq -nc \
  --arg client_id "${OPERATOR_CLIENT}" \
  --arg client_secret "${client_secret}" \
  --arg cookie_secret "${cookie_secret}" \
  '{data:{client_id:$client_id,client_secret:$client_secret,cookie_secret:$cookie_secret}}')"
write_status="$(curl -sS -o /tmp/hermes-operator-oidc-write.json -w '%{http_code}' -X POST \
  -H "X-Vault-Token: ${vault_token}" \
  -H 'Content-Type: application/json' \
  -d "${vault_payload}" \
  "${vault_addr}/v1/kv/data/atlas/hermes/operator-oidc")"
if [ "${write_status}" != "200" ] && [ "${write_status}" != "204" ]; then
  echo "Vault operator OIDC write failed (status ${write_status})" >&2
  exit 1
fi

echo "Hermes chat and operator OIDC clients are ready"
