#!/bin/bash

# Script de configuration Keycloak - Utilisateur de test
# Utilise l'API Admin REST de Keycloak pour créer l'utilisateur et les rôles

KEYCLOAK_URL="http://localhost:8180"
ADMIN_USER="admin"
ADMIN_PASSWORD="admin"
REALM="lions-user-manager"
TEST_USER="test-user"
TEST_PASSWORD="test123"
TEST_EMAIL="test@lions.dev"

echo "=========================================="
echo "Configuration Keycloak - Utilisateur Test"
echo "=========================================="
echo ""

# 1. Obtenir le token d'administration
echo "1. Authentification admin..."
TOKEN_RESPONSE=$(curl -s -X POST "${KEYCLOAK_URL}/realms/master/protocol/openid-connect/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=${ADMIN_USER}" \
  -d "password=${ADMIN_PASSWORD}" \
  -d "grant_type=password" \
  -d "client_id=admin-cli")

ACCESS_TOKEN=$(echo $TOKEN_RESPONSE | grep -o '"access_token":"[^"]*' | cut -d'"' -f4)

if [ -z "$ACCESS_TOKEN" ]; then
  echo "ERREUR: Impossible d'obtenir le token d'administration"
  echo "Réponse: $TOKEN_RESPONSE"
  exit 1
fi

echo "✓ Token obtenu"
echo ""

# 2. Vérifier/Créer le realm
echo "2. Vérification du realm '${REALM}'..."
REALM_EXISTS=$(curl -s -o /dev/null -w "%{http_code}" \
  -X GET "${KEYCLOAK_URL}/admin/realms/${REALM}" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}")

if [ "$REALM_EXISTS" != "200" ]; then
  echo "Création du realm '${REALM}'..."
  curl -s -X POST "${KEYCLOAK_URL}/admin/realms" \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    -H "Content-Type: application/json" \
    -d "{
      \"realm\": \"${REALM}\",
      \"enabled\": true
    }"
  echo "✓ Realm créé"
else
  echo "✓ Realm existe déjà"
fi
echo ""

# 3. Créer les rôles realm
echo "3. Création des rôles realm..."
ROLES=("admin" "user_manager" "user_viewer" "role_manager" "role_viewer" "auditor" "sync_manager")

for ROLE in "${ROLES[@]}"; do
  echo "  - Vérification du rôle '${ROLE}'..."
  ROLE_EXISTS=$(curl -s -o /dev/null -w "%{http_code}" \
    -X GET "${KEYCLOAK_URL}/admin/realms/${REALM}/roles/${ROLE}" \
    -H "Authorization: Bearer ${ACCESS_TOKEN}")
  
  if [ "$ROLE_EXISTS" != "200" ]; then
    curl -s -X POST "${KEYCLOAK_URL}/admin/realms/${REALM}/roles" \
      -H "Authorization: Bearer ${ACCESS_TOKEN}" \
      -H "Content-Type: application/json" \
      -d "{
        \"name\": \"${ROLE}\",
        \"description\": \"Rôle ${ROLE} pour lions-user-manager\"
      }"
    echo "    ✓ Rôle '${ROLE}' créé"
  else
    echo "    ✓ Rôle '${ROLE}' existe déjà"
  fi
done
echo ""

# 4. Créer l'utilisateur de test
echo "4. Création de l'utilisateur '${TEST_USER}'..."
USER_EXISTS=$(curl -s -o /dev/null -w "%{http_code}" \
  -X GET "${KEYCLOAK_URL}/admin/realms/${REALM}/users?username=${TEST_USER}" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}")

if [ "$USER_EXISTS" != "200" ]; then
  # Créer l'utilisateur
  USER_ID=$(curl -s -X POST "${KEYCLOAK_URL}/admin/realms/${REALM}/users" \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    -H "Content-Type: application/json" \
    -d "{
      \"username\": \"${TEST_USER}\",
      \"email\": \"${TEST_EMAIL}\",
      \"firstName\": \"Test\",
      \"lastName\": \"User\",
      \"enabled\": true,
      \"emailVerified\": true
    }" | grep -o '"id":"[^"]*' | cut -d'"' -f4)
  
  if [ -z "$USER_ID" ]; then
    # Récupérer l'ID de l'utilisateur existant
    USER_ID=$(curl -s -X GET "${KEYCLOAK_URL}/admin/realms/${REALM}/users?username=${TEST_USER}" \
      -H "Authorization: Bearer ${ACCESS_TOKEN}" | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)
  fi
  
  if [ -z "$USER_ID" ]; then
    echo "ERREUR: Impossible de créer ou récupérer l'utilisateur"
    exit 1
  fi
  
  echo "  ✓ Utilisateur créé (ID: ${USER_ID})"
  
  # Définir le mot de passe
  curl -s -X PUT "${KEYCLOAK_URL}/admin/realms/${REALM}/users/${USER_ID}/reset-password" \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    -H "Content-Type: application/json" \
    -d "{
      \"type\": \"password\",
      \"value\": \"${TEST_PASSWORD}\",
      \"temporary\": false
    }"
  echo "  ✓ Mot de passe défini"
else
  # Récupérer l'ID de l'utilisateur existant
  USER_ID=$(curl -s -X GET "${KEYCLOAK_URL}/admin/realms/${REALM}/users?username=${TEST_USER}" \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)
  echo "  ✓ Utilisateur existe déjà (ID: ${USER_ID})"
fi
echo ""

# 5. Assigner les rôles à l'utilisateur
echo "5. Attribution des rôles à l'utilisateur..."

# Récupérer les représentations des rôles
ROLE_REPRESENTATIONS="["
for i in "${!ROLES[@]}"; do
  ROLE="${ROLES[$i]}"
  ROLE_REP=$(curl -s -X GET "${KEYCLOAK_URL}/admin/realms/${REALM}/roles/${ROLE}" \
    -H "Authorization: Bearer ${ACCESS_TOKEN}")
  
  if [ $i -gt 0 ]; then
    ROLE_REPRESENTATIONS+=","
  fi
  ROLE_REPRESENTATIONS+="${ROLE_REP}"
done
ROLE_REPRESENTATIONS+="]"

# Assigner tous les rôles
curl -s -X POST "${KEYCLOAK_URL}/admin/realms/${REALM}/users/${USER_ID}/role-mappings/realm" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d "${ROLE_REPRESENTATIONS}"

echo "  ✓ Rôles assignés"
echo ""

# 6. Vérifier le client et le mapper de rôles
echo "6. Vérification du client 'lions-user-manager-client'..."
CLIENT_ID=$(curl -s -X GET "${KEYCLOAK_URL}/admin/realms/${REALM}/clients?clientId=lions-user-manager-client" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)

if [ -z "$CLIENT_ID" ]; then
  echo "  ⚠ Client 'lions-user-manager-client' non trouvé"
  echo "  Veuillez créer le client manuellement dans Keycloak"
else
  echo "  ✓ Client trouvé (ID: ${CLIENT_ID})"
  
  # Vérifier le mapper de rôles realm
  MAPPER_EXISTS=$(curl -s -X GET "${KEYCLOAK_URL}/admin/realms/${REALM}/clients/${CLIENT_ID}/protocol-mappers/models" \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" | grep -o '"name":"realm roles"')
  
  if [ -z "$MAPPER_EXISTS" ]; then
    echo "  Création du mapper 'realm roles'..."
    curl -s -X POST "${KEYCLOAK_URL}/admin/realms/${REALM}/clients/${CLIENT_ID}/protocol-mappers/models" \
      -H "Authorization: Bearer ${ACCESS_TOKEN}" \
      -H "Content-Type: application/json" \
      -d "{
        \"name\": \"realm roles\",
        \"protocol\": \"openid-connect\",
        \"protocolMapper\": \"oidc-usermodel-realm-role-mapper\",
        \"config\": {
          \"claim.name\": \"realm_access.roles\",
          \"access.token.claim\": \"true\",
          \"id.token.claim\": \"true\",
          \"userinfo.token.claim\": \"true\"
        }
      }"
    echo "  ✓ Mapper créé"
  else
    echo "  ✓ Mapper existe déjà"
  fi
fi
echo ""

echo "=========================================="
echo "Configuration terminée !"
echo "=========================================="
echo ""
echo "Informations de connexion:"
echo "  Username: ${TEST_USER}"
echo "  Password: ${TEST_PASSWORD}"
echo "  Email: ${TEST_EMAIL}"
echo ""
echo "Rôles assignés: ${ROLES[*]}"
echo ""

