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

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

KC_URL="${KEYCLOAK_SERVER:-http://keycloak.sso.svc.cluster.local}"
REALM="${KEYCLOAK_REALM:-veles}"
CLIENT_ID="${KEYCLOAK_CLIENT_ID:-gitea}"
PUBLIC_BASE_URL="${GITEA_PUBLIC_BASE_URL:-https://scm.bstein.dev}"
AUTH_SOURCE_NAME="${GITEA_AUTH_SOURCE_NAME:-veles}"
TESTER_GROUP="${VELES_GITEA_TESTER_GROUP:-veles-tester}"
VAULT_SECRET_PATH="${VAULT_SECRET_PATH:-kv/data/atlas/gitea/gitea-veles-oidc}"

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

ensure_group() {
  group_name="$1"
  groups="$(curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    "${KC_URL}/admin/realms/${REALM}/groups?search=$(printf '%s' "${group_name}" | jq -sRr @uri)" || true)"
  if echo "$groups" | jq -e --arg name "$group_name" '.[]? | select(.name == $name)' >/dev/null 2>&1; then
    return
  fi
  status="$(curl -sS -o /dev/null -w "%{http_code}" -X POST \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    -H 'Content-Type: application/json' \
    -d "$(jq -nc --arg name "$group_name" '{name:$name}')" \
    "${KC_URL}/admin/realms/${REALM}/groups")"
  if [ "$status" != "201" ] && [ "$status" != "204" ] && [ "$status" != "409" ]; then
    echo "Keycloak group create failed for ${group_name} (status ${status})" >&2
    exit 1
  fi
}

ensure_group "${TESTER_GROUP}"

CLIENT_QUERY="$(curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  "${KC_URL}/admin/realms/${REALM}/clients?clientId=$(printf '%s' "${CLIENT_ID}" | jq -sRr @uri)" || true)"
CLIENT_UUID="$(echo "$CLIENT_QUERY" | jq -r '.[0].id' 2>/dev/null || true)"

client_payload="$(jq -nc \
  --arg client_id "${CLIENT_ID}" \
  --arg root_url "${PUBLIC_BASE_URL}" \
  --arg callback "${PUBLIC_BASE_URL}/user/oauth2/${AUTH_SOURCE_NAME}/callback" \
  '{clientId:$client_id,enabled:true,protocol:"openid-connect",publicClient:false,standardFlowEnabled:true,implicitFlowEnabled:false,directAccessGrantsEnabled:false,serviceAccountsEnabled:false,redirectUris:[$callback],webOrigins:[$root_url],rootUrl:$root_url,baseUrl:"/",attributes:{"pkce.code.challenge.method":"S256","post.logout.redirect.uris":($root_url + "/*")}}')"

if [ -z "$CLIENT_UUID" ] || [ "$CLIENT_UUID" = "null" ]; then
  status="$(curl -sS -o /dev/null -w "%{http_code}" -X POST \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    -H 'Content-Type: application/json' \
    -d "${client_payload}" \
    "${KC_URL}/admin/realms/${REALM}/clients")"
  if [ "$status" != "201" ] && [ "$status" != "204" ] && [ "$status" != "409" ]; then
    echo "Keycloak client create failed for ${CLIENT_ID} (status ${status})" >&2
    exit 1
  fi
  CLIENT_QUERY="$(curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    "${KC_URL}/admin/realms/${REALM}/clients?clientId=$(printf '%s' "${CLIENT_ID}" | jq -sRr @uri)" || true)"
  CLIENT_UUID="$(echo "$CLIENT_QUERY" | jq -r '.[0].id' 2>/dev/null || true)"
fi

if [ -z "$CLIENT_UUID" ] || [ "$CLIENT_UUID" = "null" ]; then
  echo "Keycloak client ${CLIENT_ID} 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 "${client_payload}" \
  "${KC_URL}/admin/realms/${REALM}/clients/${CLIENT_UUID}")"
if [ "$status" != "200" ] && [ "$status" != "204" ]; then
  echo "Keycloak client update failed for ${CLIENT_ID} (status ${status})" >&2
  exit 1
fi

mapper_payload="$(jq -nc \
  '{name:"groups",protocol:"openid-connect",protocolMapper:"oidc-group-membership-mapper",consentRequired:false,config:{"full.path":"false","id.token.claim":"true","access.token.claim":"true","userinfo.token.claim":"true","claim.name":"groups","jsonType.label":"String"}}')"
mappers="$(curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  "${KC_URL}/admin/realms/${REALM}/clients/${CLIENT_UUID}/protocol-mappers/models" || true)"
MAPPER_ID="$(echo "$mappers" | jq -r '.[]? | select(.name == "groups") | .id' | head -n1 || true)"
if [ -n "$MAPPER_ID" ] && [ "$MAPPER_ID" != "null" ]; then
  status="$(curl -sS -o /dev/null -w "%{http_code}" -X PUT \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    -H 'Content-Type: application/json' \
    -d "${mapper_payload}" \
    "${KC_URL}/admin/realms/${REALM}/clients/${CLIENT_UUID}/protocol-mappers/models/${MAPPER_ID}")"
else
  status="$(curl -sS -o /dev/null -w "%{http_code}" -X POST \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    -H 'Content-Type: application/json' \
    -d "${mapper_payload}" \
    "${KC_URL}/admin/realms/${REALM}/clients/${CLIENT_UUID}/protocol-mappers/models")"
fi
if [ "$status" != "200" ] && [ "$status" != "201" ] && [ "$status" != "204" ]; then
  echo "Keycloak groups mapper ensure failed (status ${status})" >&2
  exit 1
fi

CLIENT_SECRET="$(curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  "${KC_URL}/admin/realms/${REALM}/clients/${CLIENT_UUID}/client-secret" | jq -r '.value' 2>/dev/null || true)"
if [ -z "$CLIENT_SECRET" ] || [ "$CLIENT_SECRET" = "null" ]; then
  echo "Keycloak client secret not found for ${CLIENT_ID}" >&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 "${CLIENT_ID}" \
  --arg client_secret "${CLIENT_SECRET}" \
  --arg discovery_url "${PUBLIC_BASE_URL}" \
  --arg issuer "https://sso.bstein.dev/realms/${REALM}" \
  --arg auto_discovery_url "https://sso.bstein.dev/realms/${REALM}/.well-known/openid-configuration" \
  --arg auth_source_name "${AUTH_SOURCE_NAME}" \
  --arg tester_group "${TESTER_GROUP}" \
  --arg group_team_map "{\"${TESTER_GROUP}\":{\"veles-alpha\":[\"testers\"]}}" \
  '{data:{client_id:$client_id,client_secret:$client_secret,issuer:$issuer,openid_auto_discovery_url:$auto_discovery_url,auth_source_name:$auth_source_name,required_claim_name:"groups",required_claim_value:$tester_group,group_claim_name:"groups",restricted_group:$tester_group,group_team_map:$group_team_map,gitea_base_url:$discovery_url}}')"

curl -sS -X POST -H "X-Vault-Token: ${vault_token}" \
  -H 'Content-Type: application/json' \
  -d "${payload}" "${vault_addr}/v1/${VAULT_SECRET_PATH}" >/dev/null

echo "Veles realm Gitea OIDC client ready"
