#!/usr/bin/env bash
set -euo pipefail
DBHOST=""; OUT=/root/trinity-connsrv-join.tar
die() { echo "ERROR: $*" >&2; exit 1; }
while [ $# -gt 0 ]; do
  case "$1" in --db-host) DBHOST="$2"; shift 2;; --out) OUT="$2"; shift 2;; -h|--help) cat <<'TRINITY_USAGE'; exit 0;; *) die "unknown option $1";; esac
  sudo trinity-connsrv-bundle [--db-host <address of the database for the connection servers>] [--out /root/trinity-connsrv-join.tar]
  --db-host replaces Host= / Server= when the portal reaches its database as localhost (single server): the connection
Documentation: https://mobileworkplaceservices.ro/docs.html
TRINITY_USAGE
done
[ "$(id -u)" = 0 ] || die "run as root (sudo)"
[[ -z "$DBHOST" || "$DBHOST" =~ ^[A-Za-z0-9][A-Za-z0-9.:-]{0,252}$ ]] || die "--db-host: a host name or address"
envs=$(systemctl show -p Environment trinity-portal 2>/dev/null | sed 's/^Environment=//')
val() { printf '%s\n' "$envs" | tr ' ' '\n' | sed -n "s/^$1=//p" | head -n1; }
CFG=$(val WSP_CONFIG); KEYF=$(val WSP_SECRET_KEY); DATA=$(val WSP_DATA)
CFG=${CFG:-/etc/trinity/trinity.json}; KEYF=${KEYF:-/etc/trinity/secret.key}; DATA=${DATA:-/var/lib/trinity}
[ -s "$CFG" ] || die "portal configuration $CFG not found (is this the TRINITY portal?)"
[ -s "$KEYF" ] || die "secret key $KEYF not found"
t=$(mktemp -d); trap 'rm -rf "$t"' EXIT; chmod 700 "$t"
python3 - "$CFG" "$t/trinity.json" "$DBHOST" <<'PY'
import json, re, sys
src, dst, host = sys.argv[1:4]
d = json.load(open(src, encoding='utf-8-sig'))
a = d.get("appSettings", {}); cs = (d.get("connectionStrings") or {}).get("MonitorDb", "")
keep = {k: a[k] for k in ("DbProvider", "DbCloud", "EngineLockGraceSeconds") if k in a}
if host and cs:
    cs = re.sub(r'(?i)(^|;)\s*(Host|Server|Data Source)\s*=\s*[^;]*', lambda m: m.group(1) + m.group(2) + "=" + host, cs)
if not cs: print("NOTE: no database connection in " + src + " - the connection in Settings -> Database is used (db-connection.json)")
elif re.search(r'(?i)(Host|Server|Data Source)\s*=\s*(localhost|127\.0\.0\.1|::1)\b', cs): print("WARNING: the database is reached as localhost - the connection servers cannot use that: give --db-host")
json.dump({"appSettings": keep, "connectionStrings": {"MonitorDb": cs} if cs else {}}, open(dst, "w"), indent=2)
PY
install -m 600 "$KEYF" "$t/secret.key"
files="trinity.json secret.key"
if [ -s "$DATA/App_Data/db-connection.json" ]; then install -m 600 "$DATA/App_Data/db-connection.json" "$t/db-connection.json"; files="$files db-connection.json"; fi
# shellcheck disable=SC2086
(umask 077; tar -C "$t" -cf "$OUT" $files)
chmod 600 "$OUT"
echo "Join file: $OUT (0600, contains the database password and the secret key) - copy it to the first connection server,"
echo "run install-trinity-connsrv.sh --join $(basename "$OUT") there, then delete it on both machines."
