#!/bin/bash

set -eu

mkdir -p /app/data/data /app/data/configs /run/synapse
mkdir -p "${MAS_KEYS_DIR}"

source /app/code/env/bin/activate

MAS_PORT=${MAS_PORT:-4000}
MAS_DOMAIN=${MAS_DOMAIN:-auth.${CLOUDRON_APP_DOMAIN}}
MAS_SECRET_FILE=/app/data/configs/mas-client-secret
MAS_CONFIG_TEMPLATE=/app/pkg/mas/mas-config.template.yaml
MAS_CONFIG_OUTPUT=/app/data/configs/mas.yaml
MAS_CLI_BIN=/app/pkg/mas/mas-cli
MAS_KEYS_DIR=/app/data/configs/mas-keys
MAS_OIDC_CLIENT_ID=${MAS_OIDC_CLIENT_ID:-synapse}
MAS_OIDC_ISSUER=${MAS_OIDC_ISSUER:-https://${MAS_DOMAIN}}
MAS_OIDC_AUTH_ENDPOINT=${MAS_OIDC_AUTH_ENDPOINT:-${MAS_OIDC_ISSUER}/oauth2/authorize}
MAS_OIDC_TOKEN_ENDPOINT=${MAS_OIDC_TOKEN_ENDPOINT:-${MAS_OIDC_ISSUER}/oauth2/token}
MAS_OIDC_USERINFO_ENDPOINT=${MAS_OIDC_USERINFO_ENDPOINT:-${MAS_OIDC_ISSUER}/oauth2/userinfo}
MAS_OIDC_SCOPES=${MAS_OIDC_SCOPES:-"openid profile email"}
export MAS_PORT MAS_DOMAIN MAS_CONFIG_TEMPLATE MAS_CONFIG_OUTPUT MAS_CLI_BIN
export MAS_OIDC_CLIENT_ID MAS_OIDC_CLIENT_SECRET MAS_OIDC_ISSUER MAS_OIDC_AUTH_ENDPOINT MAS_OIDC_TOKEN_ENDPOINT MAS_OIDC_USERINFO_ENDPOINT MAS_OIDC_SCOPES MAS_KEYS_DIR

# ensure we have a persistent MAS client secret for the Synapse OIDC client
if [[ -f "${MAS_SECRET_FILE}" ]]; then
    MAS_OIDC_CLIENT_SECRET=$(cat "${MAS_SECRET_FILE}")
else
    MAS_OIDC_CLIENT_SECRET=$(pwgen -1s 64)
    echo "${MAS_OIDC_CLIENT_SECRET}" > "${MAS_SECRET_FILE}"
    chmod 600 "${MAS_SECRET_FILE}"
fi
export MAS_OIDC_CLIENT_SECRET

# ensure postgres port is always defined for the MAS template
export CLOUDRON_POSTGRESQL_PORT=${CLOUDRON_POSTGRESQL_PORT:-5432}

if [[ ! -f /app/data/configs/homeserver.yaml ]]; then
    echo "==> Detected first run"

    # this is set at installation time and not changed after
    server_name=$(python -c "from publicsuffix2 import get_sld; print(get_sld('${CLOUDRON_APP_DOMAIN}'));")

    python3 -m synapse.app.homeserver \
        --server-name ${server_name} \
        --config-path /app/data/configs/homeserver.yaml \
        --config-directory /app/data/configs \
        --data-directory /app/data/data \
        --generate-config \
        --report-stats=no

    # fix logging configuration
    cp /app/pkg/homeserver.yaml.template /app/data/configs/homeserver.yaml
    mv /app/data/configs/${server_name}.log.config /app/data/configs/log.config
    yq eval -i ".log_config=\"/app/data/configs/log.config\"" /app/data/configs/homeserver.yaml

    # delete default file and buffer handlers
    yq eval -i "del(.handlers.file)" /app/data/configs/log.config
    yq eval -i "del(.handlers.buffer)" /app/data/configs/log.config

    mv /app/data/configs/${server_name}.signing.key /app/data/configs/signing.key

    yq eval -i ".server_name=\"${server_name}\"" /app/data/configs/homeserver.yaml
    yq eval -i ".registration_shared_secret=\"$(pwgen -1s 64)\"" /app/data/configs/homeserver.yaml
    yq eval -i ".macaroon_secret_key=\"$(pwgen -1s 64)\"" /app/data/configs/homeserver.yaml
    yq eval -i ".form_secret=\"$(pwgen -1s 64)\"" /app/data/configs/homeserver.yaml

    if [[ -z "${CLOUDRON_OIDC_ISSUER:-}" ]]; then
        yq eval -i ".enable_registration=true" /app/data/configs/homeserver.yaml
        yq eval -i ".password_config.enabled=true" /app/data/configs/homeserver.yaml
        yq eval -i ".password_config.localdb_enabled=true" /app/data/configs/homeserver.yaml
        yq eval -i "del(.oidc_providers)" /app/data/configs/homeserver.yaml
    fi
    yq eval -i ".password_config.pepper=\"$(pwgen -1s 12)\"" /app/data/configs/homeserver.yaml # always set this so that users can enable password login if needed
fi

echo "==> Ensure we log to console"
yq eval -i ".root.handlers=[\"console\"]" /app/data/configs/log.config
yq eval -i ".loggers.twisted.handlers=[\"console\"]" /app/data/configs/log.config

[[ ! -f /app/data/index.html ]] && cp /app/pkg/index.html /app/data/index.html

echo "==> Configuring synapse"
yq eval -i ".public_baseurl=\"${CLOUDRON_APP_ORIGIN}\"" /app/data/configs/homeserver.yaml

# database
yq eval -i ".database.args.user=\"${CLOUDRON_POSTGRESQL_USERNAME}\"" /app/data/configs/homeserver.yaml
yq eval -i ".database.args.password=\"${CLOUDRON_POSTGRESQL_PASSWORD}\"" /app/data/configs/homeserver.yaml
yq eval -i ".database.args.database=\"${CLOUDRON_POSTGRESQL_DATABASE}\"" /app/data/configs/homeserver.yaml
yq eval -i ".database.args.host=\"${CLOUDRON_POSTGRESQL_HOST}\"" /app/data/configs/homeserver.yaml

# email
yq eval -i ".email.smtp_host=\"${CLOUDRON_MAIL_SMTP_SERVER}\"" /app/data/configs/homeserver.yaml
yq eval -i ".email.smtp_port=${CLOUDRON_MAIL_SMTP_PORT}" /app/data/configs/homeserver.yaml
yq eval -i ".email.smtp_user=\"${CLOUDRON_MAIL_SMTP_USERNAME}\"" /app/data/configs/homeserver.yaml
yq eval -i ".email.smtp_pass=\"${CLOUDRON_MAIL_SMTP_PASSWORD}\"" /app/data/configs/homeserver.yaml
yq eval -i ".email.notif_from=\"${CLOUDRON_MAIL_FROM_DISPLAY_NAME:-Matrix} <${CLOUDRON_MAIL_FROM}>\"" /app/data/configs/homeserver.yaml

# oidc
if [[ -n "${CLOUDRON_OIDC_ISSUER:-}" ]]; then
    echo " ==> Configuring OIDC auth"
    yq eval -i ".oidc_providers[0].idp_id=\"cloudron\"" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].idp_name=\"${CLOUDRON_OIDC_PROVIDER_NAME:-Cloudron}\"" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].issuer=\"${CLOUDRON_OIDC_ISSUER}\"" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].client_id=\"${CLOUDRON_OIDC_CLIENT_ID}\"" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].client_secret=\"${CLOUDRON_OIDC_CLIENT_SECRET}\"" /app/data/configs/homeserver.yaml

    yq eval -i ".oidc_providers[0].scopes=[\"openid\", \"email\", \"profile\"]" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].authorization_endpoint=\"${CLOUDRON_OIDC_AUTH_ENDPOINT}\"" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].token_endpoint=\"${CLOUDRON_OIDC_TOKEN_ENDPOINT}\"" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].userinfo_endpoint=\"${CLOUDRON_OIDC_PROFILE_ENDPOINT}\"" /app/data/configs/homeserver.yaml
    # https://s3lph.me/ldap-to-oidc-migration-3-matrix.html
    yq eval -i ".oidc_providers[0].allow_existing_users=true" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].skip_verification=true" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].user_mapping_provider.config.localpart_template=\"{{ user.sub }}\"" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].user_mapping_provider.config.display_name_template=\"{{ user.name }}\"" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].user_mapping_provider.config.email_template=\"{{ user.email }}\"" /app/data/configs/homeserver.yaml
else
    yq eval -i ".password_config.localdb_enabled=true" /app/data/configs/homeserver.yaml
fi

if [[ -x "${MAS_CLI_BIN}" ]]; then
    echo "==> Configuring Synapse to trust MAS"
    # ensure oidc_providers[0] exists
    yq eval -i '.oidc_providers[0] = (.oidc_providers[0] // {})' /app/data/configs/homeserver.yaml

    yq eval -i ".enable_registration=false" /app/data/configs/homeserver.yaml
    yq eval -i ".password_config.enabled=false" /app/data/configs/homeserver.yaml
    yq eval -i ".password_config.localdb_enabled=false" /app/data/configs/homeserver.yaml

    yq eval -i ".oidc_providers[0].idp_id=\"mas\"" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].idp_name=\"MAS\"" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].issuer=\"${MAS_OIDC_ISSUER}\"" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].client_id=\"${MAS_OIDC_CLIENT_ID}\"" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].client_secret=\"${MAS_OIDC_CLIENT_SECRET}\"" /app/data/configs/homeserver.yaml

    yq eval -i ".oidc_providers[0].scopes=[\"openid\", \"profile\", \"email\"]" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].authorization_endpoint=\"${MAS_OIDC_AUTH_ENDPOINT}\"" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].token_endpoint=\"${MAS_OIDC_TOKEN_ENDPOINT}\"" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].userinfo_endpoint=\"${MAS_OIDC_USERINFO_ENDPOINT}\"" /app/data/configs/homeserver.yaml

    yq eval -i ".oidc_providers[0].allow_existing_users=true" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].skip_verification=true" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].user_mapping_provider.config.localpart_template=\"{{ user.sub }}\"" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].user_mapping_provider.config.display_name_template=\"{{ user.name }}\"" /app/data/configs/homeserver.yaml
    yq eval -i ".oidc_providers[0].user_mapping_provider.config.email_template=\"{{ user.email }}\"" /app/data/configs/homeserver.yaml
fi

# turn (https://github.com/matrix-org/synapse/blob/master/docs/turn-howto.md#synapse-setup)
if [[ -n "${CLOUDRON_TURN_SERVER:-}" ]]; then
    yq eval -i ".turn_uris=[]" /app/data/configs/homeserver.yaml
    yq eval -i ".turn_uris[0]=\"turn:${CLOUDRON_TURN_SERVER}:${CLOUDRON_TURN_TLS_PORT}?transport=udp\"" /app/data/configs/homeserver.yaml
    yq eval -i ".turn_uris[1]=\"turn:${CLOUDRON_TURN_SERVER}:${CLOUDRON_TURN_TLS_PORT}?transport=tcp\"" /app/data/configs/homeserver.yaml
    yq eval -i ".turn_shared_secret=\"${CLOUDRON_TURN_SECRET}\"" /app/data/configs/homeserver.yaml
fi

if [[ -f "${MAS_CONFIG_TEMPLATE}" && ! -f "${MAS_CONFIG_OUTPUT}" ]]; then
    python3 - <<'PY'
import os
from pathlib import Path
from string import Template

template = Path(os.environ["MAS_CONFIG_TEMPLATE"])
dest = Path(os.environ["MAS_CONFIG_OUTPUT"])
dest.write_text(Template(template.read_text()).substitute(os.environ))
PY
fi

# fix permissions
echo "==> Fixing permissions"
chown -R cloudron:cloudron /app/data /run/synapse

echo "==> Starting synapse"
mas_pid=
synapse_pid=

terminate_services() {
    [[ -n "${synapse_pid}" ]] && kill -TERM "${synapse_pid}" 2>/dev/null || true
    [[ -n "${mas_pid}" ]] && kill -TERM "${mas_pid}" 2>/dev/null || true
}
trap 'terminate_services' TERM INT
trap '[[ -n "${mas_pid}" ]] && kill -TERM "${mas_pid}" 2>/dev/null || true' EXIT

if [[ -x "${MAS_CLI_BIN}" ]]; then
    echo "==> Launching MAS server"
    gosu cloudron:cloudron "${MAS_CLI_BIN}" server --config "${MAS_CONFIG_OUTPUT}" &
    mas_pid=$!
else
    echo "==> MAS CLI not present at ${MAS_CLI_BIN}; skipping MAS launch"
fi

gosu cloudron:cloudron python3 -m synapse.app.homeserver --config-path /app/data/configs/homeserver.yaml -n &
synapse_pid=$!

wait "${synapse_pid}"
status=$?

terminate_services
exit "${status}"
