#!/bin/bash

# Script pour récupérer le secret du client Keycloak

KEYCLOAK_URL="http://localhost:8180"
REALM="lions-user-manager"

# 1. Obtenir le token admin
TOKEN=$(curl -s -X POST "${KEYCLOAK_URL}/realms/master/protocol/openid-connect/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=admin" \
  -d "password=admin" \
  -d "grant_type=password" \
  -d "client_id=admin-cli" | grep -o '"access_token":"[^"]*' | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
  echo "Erreur: Impossible d'obtenir le token"
  exit 1
fi

# 2. Récupérer tous les clients
CLIENTS=$(curl -s -X GET "${KEYCLOAK_URL}/admin/realms/${REALM}/clients" \
  -H "Authorization: Bearer ${TOKEN}")

# 3. Extraire l'ID du client
CLIENT_ID=$(echo "$CLIENTS" | grep -B 5 '"clientId":"lions-user-manager-client"' | grep '"id"' | head -1 | grep -o '"id":"[^"]*' | cut -d'"' -f4)

if [ -z "$CLIENT_ID" ]; then
  echo "Erreur: Client non trouvé"
  exit 1
fi

echo "Client ID interne: $CLIENT_ID"

# 4. Récupérer le secret du client
SECRET=$(curl -s -X GET "${KEYCLOAK_URL}/admin/realms/${REALM}/clients/${CLIENT_ID}/client-secret" \
  -H "Authorization: Bearer ${TOKEN}" | grep -o '"value":"[^"]*' | cut -d'"' -f4)

if [ -z "$SECRET" ]; then
  echo "Erreur: Secret non trouvé"
  exit 1
fi

echo ""
echo "=== Secret du client lions-user-manager-client ==="
echo "Secret: $SECRET"
echo ""
echo "Mettre à jour dans application-dev.properties:"
echo "quarkus.oidc.credentials.secret=$SECRET"
