# 0. Source your env (Authentik bootstrap token + Vault addr)
set -a && source ~/.authentik/.env && set +a
VAULT_ADDR="http://vault.riotpiao.com"
AUTHENTIK_URL="http://authentik.riotpiao.com"

# 1. Fetch the real client_id + client_secret from Authentik
PROVIDER_PK=$(curl -s \
  -H "Authorization: Bearer ${AUTHENTIK_BOOTSTRAP_TOKEN}" \
  "${AUTHENTIK_URL}/api/v3/providers/oauth2/?name=talos-cli-shell" \
  | python3 -c "import json,sys; r=json.load(sys.stdin)['results']; print(r[0]['pk'] if r else 'NOT_FOUND')")

echo "Provider PK: ${PROVIDER_PK}"

CLIENT_ID=$(curl -s \
  -H "Authorization: Bearer ${AUTHENTIK_BOOTSTRAP_TOKEN}" \
  "${AUTHENTIK_URL}/api/v3/providers/oauth2/${PROVIDER_PK}/" \
  | python3 -c "import json,sys; p=json.load(sys.stdin); print(p['client_id'])")

CLIENT_SECRET=$(curl -s \
  -H "Authorization: Bearer ${AUTHENTIK_BOOTSTRAP_TOKEN}" \
  "${AUTHENTIK_URL}/api/v3/providers/oauth2/${PROVIDER_PK}/" \
  | python3 -c "import json,sys; p=json.load(sys.stdin); print(p['client_secret'])")

echo "client_id: ${CLIENT_ID}"

# 2. Get a JWT from Authentik (client credentials flow)
# JWT=$(curl -s -X POST \
#   "${AUTHENTIK_URL}/application/o/talos-cli-shell/token/" \
#   -d "grant_type=client_credentials&client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&scope=openid" \
#   | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('access_token', d))")
# echo "JWT: ${JWT}..."

curl -v -s -X POST \
  "${AUTHENTIK_URL}/application/o/homelab-mac-cli/token/" \
  -d "grant_type=client_credentials&client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&scope=openid"

# # 3. Exchange JWT for a Vault token
# VAULT_TOKEN=$(curl -s -X POST \
#   "${VAULT_ADDR}/v1/auth/jwt/login" \
#   -H "Content-Type: application/json" \
#   -d "{\"jwt\": \"${JWT}\", \"role\": \"shell\"}" \
#   | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('auth',{}).get('client_token', d))")

# echo "Vault token: ${VAULT_TOKEN:0:20}..."

# # 4. Verify the token works
# curl -s -H "X-Vault-Token: ${VAULT_TOKEN}" \
#   "${VAULT_ADDR}/v1/auth/token/lookup-self" \
#   | python3 -c "import json,sys; d=json.load(sys.stdin); print('policies:', d['data']['policies'])"
