#!/bin/bash
die() { echo >&2 "$@" ; exit 1 ; }

DIRNAME="$(dirname $0)"
cd "$DIRNAME"
source ../env.production || die "no top levle env?"
source env.production || die "no local env?"

docker-compose down

HOMESERVER_YAML="data/synapse/homeserver.yaml"
if [  -r "$HOMESERVER_YAML" ]; then
	echo "home server already configured? delete data directory to force reconfig"
	exit 0
fi

# This will create a *delegated* matrix server,
# where the "servername" is just the top level domain,
# but it is hosted on "matrix.DOMAIN_NAME".
# the syntax here is confusing and it is not clear in
# the docs *which* have to be updated.
docker run -it --rm \
	-v "`pwd`/data/synapse:/data" \
	-e "SYNAPSE_SERVER_NAME=$DOMAIN_NAME" \
	-e SYNAPSE_REPORT_STATS=yes \
	matrixdotorg/synapse:latest generate \
|| die "unable to generate synapse config"

MATRIX_CLIENT_SECRET="$(openssl rand -hex 20)"

cat <<EOF >> "$HOMESERVER_YAML"
web_client_location: https://${MATRIX_HOSTNAME}/
public_baseurl: https://${MATRIX_HOSTNAME}/
oidc_providers:
  - idp_id: keycloak
    idp_name: "KeyCloak"
    issuer: "https://${KEYCLOAK_HOSTNAME}/realms/${REALM}"
    client_id: "synapse"
    client_secret: "${MATRIX_CLIENT_SECRET}"
    scopes: ["openid", "profile"]
    user_mapping_provider:
      config:
        localpart_template: "{{ user.preferred_username }}"
        display_name_template: "{{ user.name }}"
EOF

../keycloak/client-delete 'synapse' || echo "client did not exist?"

../keycloak/client-create << EOF || die "unable to create client id"
{
	"clientId": "synapse",
	"rootUrl": "https://$MATRIX_HOSTNAME/",
	"adminUrl": "https://$MATRIX_HOSTNAME/",
	"redirectUris": [ "https://$MATRIX_HOSTNAME/*" ],
	"webOrigins": [ "https://$MATRIX_HOSTNAME" ],
	"clientAuthenticatorType": "client-secret",
	"secret": "$MATRIX_CLIENT_SECRET"
}
EOF