Add script to add `sourcearcade` realm to Keycloak
diff --git a/keycloak/init/sa-up b/keycloak/init/sa-up
new file mode 100644
index 0000000..768c784
--- /dev/null
+++ b/keycloak/init/sa-up
@@ -0,0 +1,97 @@
+#!/bin/sh
+
+set -eu
+
+kca() {
+ /opt/keycloak/bin/kcadm.sh "$@"
+}
+
+kca_cred() {
+ kca config credentials \
+ --server http://keycloak:8080 \
+ --realm master \
+ --user ${KEYCLOAK_ADMIN} \
+ --password ${KEYCLOAK_ADMIN_PASSWORD}
+}
+
+secret() {
+ seed=$(cat /run/secrets/seed)
+ printf "%s:%40s" "${seed}" "$*" | sha256sum | sed 's/[[:space:]].*//'
+}
+
+i=15
+sleep ${i} # give it a moment to come up
+while kca_cred 2>&1 | grep -q 'Connection refused\|Bad Gateway'; do
+ if [ ${i} -eq 60 ]; then
+ echo "ERROR: Couldn't login to Keycloak after ${i}s."
+ exit 1
+ fi
+ echo Waiting...
+ sleep 1
+ i=$((i+1))
+done
+if ! kca_cred; then
+ echo "ERROR: Failed to login to Keycloak."
+ exit 2
+fi
+
+REALM=${SA_REALM:-sourcearcade}
+if kca get realms/${REALM} --fields id >/dev/null 2>&1; then
+ echo Realm ${REALM} already set up.
+else
+ kca create realms -f - <<EOF
+ {
+ "realm" : "${REALM}",
+ "enabled" : true,
+ "sslRequired" : "all",
+ "registrationAllowed" : true,
+ "resetPasswordAllowed" : true,
+ "rememberMe" : true,
+ "verifyEmail" : true,
+ "smtpServer" : {
+ "host" : "mail.${SA_PUBLIC_DOMAIN_NAME}",
+ "port" : "465",
+ "auth" : true,
+ "ssl" : true,
+ "user" : "keycloak@${SA_PUBLIC_DOMAIN_NAME}",
+ "password" : "$(secret mail:keycloak)",
+ "from" : "keycloak@${SA_PUBLIC_DOMAIN_NAME}",
+ "fromDisplayName" : "SourceArcade"
+ },
+ "identityProviders" : [ {
+ "alias" : "github",
+ "providerId" : "github",
+ "enabled" : true,
+ "config" : {
+ "clientId" : "${GITHUB_OAUTH_CLIENT_ID}",
+ "clientSecret" : "${GITHUB_OAUTH_CLIENT_SECRET}"
+ }
+ } ]
+ }
+EOF
+
+ ac_id=$(kca get clients -r ${REALM} -q clientId=account-console --fields id \
+ | sed -n 's/.*"id" : "\(.*\)".*/\1/p')
+ kca update clients/${ac_id} -r ${REALM} -s webOrigins='[ "+" ]'
+
+ echo New realm ${REALM} set up.
+fi
+
+if kca get clients -r ${REALM} -q clientId=gerrit --fields clientId | grep -q gerrit; then
+ echo Gerrit client in realm ${REALM} already set up.
+else
+ kca create clients -r ${REALM} -f - <<EOF
+ {
+ "clientId" : "gerrit",
+ "name" : "Gerrit",
+ "enabled" : true,
+ "description" : "SourceArcade review platform",
+ "rootUrl" : "https://review.${SA_PUBLIC_DOMAIN_NAME}",
+ "clientAuthenticatorType" : "client-secret",
+ "secret" : "$(secret kc:gerrit)",
+ "protocol" : "openid-connect",
+ "directAccessGrantsEnabled" : false
+ }
+EOF
+ echo Gerrit client in realm ${REALM} set up.
+fi