#!/bin/bash
set -euo pipefail

# GoAlert runtime setup for Cloudron:
#   1. wait for the postgresql addon (GoAlert's startup runs migrations
#      itself, but gives up quickly if the DB is slow to accept - the
#      /dev/tcp wait removes that race)
#   2. persist GOALERT_DATA_ENCRYPTION_KEY (rotating it loses encrypted
#      notification-provider credentials)
#   3. map the Cloudron addon + platform env onto GOALERT_* vars
#   4. exec /usr/bin/goalert (migrations + web/API on :8081)
#
# Authentication: OIDC via the Cloudron platform provider. OIDC users
# are created on first login (NewUsers=true); they arrive WITHOUT
# admin rights - an admin logs in once with basic auth (GOALERT_BASIC_AUTH
# below, set only when the operator provides GOALERT_ADMIN_USER/PASS env)
# or via OIDC and is promoted from the admin panel.

DATA_DIR="/app/data"
KEY_FILE="${DATA_DIR}/.data_encryption_key"

mkdir -p "${DATA_DIR}"

# --- 1. wait for the addon -------------------------------------------------------
wait_tcp() {
  local host="$1" port="$2" name="$3"
  echo "Waiting for ${name} at ${host}:${port} ..."
  until (exec 3<>"/dev/tcp/${host}/${port}") 2>/dev/null; do
    echo "${name} is unavailable - sleeping"
    sleep 2
  done
  echo "${name} is up"
}

DB_HOST="${CLOUDRON_POSTGRESQL_HOST:-127.0.0.1}"
DB_PORT="${CLOUDRON_POSTGRESQL_PORT:-5432}"
DB_NAME="${CLOUDRON_POSTGRESQL_DATABASE:-goalert}"
DB_USER="${CLOUDRON_POSTGRESQL_USERNAME:-goalert}"
DB_PASS="${CLOUDRON_POSTGRESQL_PASSWORD:-}"

wait_tcp "${DB_HOST}" "${DB_PORT}" "PostgreSQL"

# --- 2. persistent data-encryption key -------------------------------------------
if [[ ! -s "${KEY_FILE}" ]]; then
  ( umask 077; head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n' > "${KEY_FILE}" )
  echo "Generated new data encryption key"
fi

# --- 3. Cloudron -> GOALERT_* environment ----------------------------------------
export GOALERT_DB_URL="postgres://${DB_USER}:${DB_PASS}@${DB_HOST}:${DB_PORT}/${DB_NAME}?sslmode=disable"
export GOALERT_PUBLIC_URL="${CLOUDRON_APP_ORIGIN:-http://localhost}"
export GOALERT_DATA_ENCRYPTION_KEY="$(cat "${KEY_FILE}")"
export GOALERT_LISTEN=":8081"

# optional admin bootstrap: when GOALERT_ADMIN_USER/GOALERT_ADMIN_PASS
# are set as app env vars, basic auth allows the first admin login
# (promote/deactivate the account after SSO users exist)
if [[ -n "${GOALERT_ADMIN_USER:-}" && -n "${GOALERT_ADMIN_PASS:-}" ]]; then
  export GOALERT_BASIC_AUTH="${GOALERT_ADMIN_USER}:${GOALERT_ADMIN_PASS}"
else
  unset GOALERT_BASIC_AUTH || true
fi

# platform OIDC provider -> goalert oidc config
export GOALERT_OIDC_ENABLE="${GOALERT_OIDC_ENABLE:-true}"
export GOALERT_OIDC_ISSUER_URL="${CLOUDRON_OIDC_ISSUER:-}"
export GOALERT_OIDC_CLIENT_ID="${CLOUDRON_OIDC_CLIENT_ID:-}"
export GOALERT_OIDC_CLIENT_SECRET="${CLOUDRON_OIDC_CLIENT_SECRET:-}"
export GOALERT_OIDC_NEWUSERS="${GOALERT_OIDC_NEWUSERS:-true}"
export GOALERT_OIDC_OVERRIDE_NAME="${GOALERT_OIDC_OVERRIDE_NAME:-Cloudron}"

echo "Starting GoAlert (migrations run automatically) ..."
exec /usr/bin/goalert
