#!/usr/bin/env sh set -eu if [ ! -f .env ]; then echo "missing .env" >&2 exit 1 fi set -a . ./.env set +a : "${KC_BOOTSTRAP_ADMIN_USERNAME:?set KC_BOOTSTRAP_ADMIN_USERNAME in .env}" : "${KC_BOOTSTRAP_ADMIN_PASSWORD:?set KC_BOOTSTRAP_ADMIN_PASSWORD in .env}" : "${GOOGLE_CLIENT_ID:?set GOOGLE_CLIENT_ID in .env}" : "${GOOGLE_CLIENT_SECRET:?set GOOGLE_CLIENT_SECRET in .env}" keycloak_url="${KEYCLOAK_URL:-http://localhost:8080}" realm="${KEYCLOAK_REALM:-keycloak-patterns}" admin_token="$( curl -fsS \ -d client_id=admin-cli \ -d grant_type=password \ -d "username=$KC_BOOTSTRAP_ADMIN_USERNAME" \ -d "password=$KC_BOOTSTRAP_ADMIN_PASSWORD" \ "$keycloak_url/realms/master/protocol/openid-connect/token" | jq -er .access_token )" payload="$( jq -n \ --arg client_id "$GOOGLE_CLIENT_ID" \ --arg client_secret "$GOOGLE_CLIENT_SECRET" \ '{ alias: "google", displayName: "Sign in with Google", providerId: "google", enabled: true, updateProfileFirstLoginMode: "off", trustEmail: false, storeToken: false, addReadTokenRoleOnCreate: false, authenticateByDefault: false, linkOnly: false, firstBrokerLoginFlowAlias: "first broker login", config: { clientId: $client_id, clientSecret: $client_secret, defaultScope: "openid profile email", syncMode: "IMPORT" } }' )" endpoint="$keycloak_url/admin/realms/$realm/identity-provider/instances" status="$( curl -sS -o /dev/null -w '%{http_code}' \ -H "Authorization: Bearer $admin_token" \ "$endpoint/google" )" if [ "$status" = "200" ]; then curl -fsS -X PUT \ -H "Authorization: Bearer $admin_token" \ -H "Content-Type: application/json" \ --data "$payload" \ "$endpoint/google" action="updated" else curl -fsS -X POST \ -H "Authorization: Bearer $admin_token" \ -H "Content-Type: application/json" \ --data "$payload" \ "$endpoint" action="created" fi echo "Google Identity Provider $action for realm '$realm'" echo "Register this exact Google redirect URI:" echo "$keycloak_url/realms/$realm/broker/google/endpoint"