#!/bin/sh
set -eu

KEYCLOAK_URL="${KEYCLOAK_URL:-http://keycloak:8080/auth}"
KEYCLOAK_REALM="${KEYCLOAK_REALM:-chesscubing}"
KEYCLOAK_CLIENT_ID="${KEYCLOAK_CLIENT_ID:-chesscubing-web}"
KEYCLOAK_ADMIN_USERNAME="${KEYCLOAK_ADMIN_USERNAME:-admin}"
KEYCLOAK_ADMIN_PASSWORD="${KEYCLOAK_ADMIN_PASSWORD:-admin}"

echo "Attente de Keycloak..."
until /opt/keycloak/bin/kcadm.sh config credentials \
  --server "$KEYCLOAK_URL" \
  --realm master \
  --user "$KEYCLOAK_ADMIN_USERNAME" \
  --password "$KEYCLOAK_ADMIN_PASSWORD" >/dev/null 2>&1; do
  sleep 2
done

CLIENT_INTERNAL_ID="$(
  /opt/keycloak/bin/kcadm.sh get clients \
    -r "$KEYCLOAK_REALM" \
    -q clientId="$KEYCLOAK_CLIENT_ID" \
    --fields id \
    --format csv \
    --noquotes | tail -n 1
)"

if [ -z "$CLIENT_INTERNAL_ID" ]; then
  echo "Client Keycloak introuvable: $KEYCLOAK_CLIENT_ID"
  exit 1
fi

/opt/keycloak/bin/kcadm.sh update "clients/$CLIENT_INTERNAL_ID" \
  -r "$KEYCLOAK_REALM" \
  -s directAccessGrantsEnabled=true \
  -s standardFlowEnabled=true \
  -s publicClient=true >/dev/null

/opt/keycloak/bin/kcadm.sh update "realms/$KEYCLOAK_REALM" \
  -s registrationAllowed=true \
  -s loginWithEmailAllowed=true >/dev/null

echo "Configuration Keycloak synchronisee."
