#!/bin/sh
set -e

# Get Keycloak Admin token
admin_token=$(curl --location --request POST 'http://keycloak:8180/realms/master/protocol/openid-connect/token' --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'username=admin' --data-urlencode 'password=admin' --data-urlencode 'grant_type=password' --data-urlencode 'client_id=admin-cli' | jq -r '.access_token')

# Create cesamsi user
curl --location --request POST 'http://keycloak:8180/admin/realms/anis/users' --header 'Content-Type: application/json' --header "Authorization: Bearer $admin_token" --data-raw '{"firstName":"cesam-si","lastName":"cesam-si", "email":"cesamsi@lam.fr", "enabled":"true", "emailVerified":"true", "credentials":[{"type":"password","value":"admin","temporary":false}]}'

# Get anis_admin role and id_user
anis_admin_role=$(curl --location --request GET 'http://keycloak:8180/admin/realms/anis/roles/anis_admin'  --header 'Content-Type: application/json' --header "Authorization: Bearer $admin_token")
id_user=$(curl --location --request GET 'http://keycloak:8180/admin/realms/anis/users' --header 'Content-Type: application/json' --header "Authorization: Bearer $admin_token" | jq -r '.[0]' | jq -r '.id')

# Add anis_admin role to cesamsi user
curl --location --request POST "http://keycloak:8180/admin/realms/anis/users/${id_user}/role-mappings/realm" --header 'Content-Type: application/json' --header "Authorization: Bearer $admin_token" --data-raw "[${anis_admin_role}]"
