#!/usr/bin/env bash
set -euo pipefail
D=/var/lib/trinity-recsrv/App_Data/recsrv
if [ -r /etc/trinity-recsrv/trinity.json ] && python3 -c 'import json,sys; sys.exit(0 if json.load(open("/etc/trinity-recsrv/trinity.json")).get("appSettings",{}).get("RecSrvCluster")=="true" else 1)' 2>/dev/null; then
  D="$(python3 -c 'import json; print(json.load(open("/etc/trinity-recsrv/trinity.json"))["appSettings"]["RecSrvStore"])')/.recsrv"
fi
port() { sed -n 's/^Environment=WSP_HTTPS_PORT=//p' /etc/systemd/system/trinity-recsrv.service | head -n1; }
case "${1:-status}" in
  status)
    systemctl --no-pager --lines=0 status trinity-recsrv || true
    curl -sk "https://127.0.0.1:$(port)/healthz" || echo "(not answering on port $(port))"; echo
    if [ -s "$D/pair-code.txt" ]; then echo "Pairing code (24 h): $(cat "$D/pair-code.txt")"; fi
    for f in /run/trinity-cluster/*.state; do [ -f "$f" ] && echo "VIP (keepalived $(basename "$f" .state)): $(cat "$f")"; done
    [ -r /etc/trinity-recsrv/tls.crt ] && echo "Certificate SHA-256: $(openssl x509 -in /etc/trinity-recsrv/tls.crt -outform DER 2>/dev/null | sha256sum | cut -d' ' -f1)"
    if [ -r "$D/pairing.json" ]; then python3 -c 'import json,sys
for p in json.load(open(sys.argv[1])).get("pairs") or []: print("Paired: %s (%s, %s) key %s" % (p.get("name"), p.get("ip"), p.get("paired"), p.get("fp") or "-"))' "$D/pairing.json"; fi
    ;;
  code)
    [ "$(id -u)" = 0 ] || { echo "run with sudo" >&2; exit 1; }
    rm -f "$D/pair-code.txt"; touch "$D/new-code.request"; chown trinity-recsrv:trinity-recsrv "$D/new-code.request"
    for _ in $(seq 1 20); do [ -s "$D/pair-code.txt" ] && break; sleep 1; done
    [ -s "$D/pair-code.txt" ] || { echo "the service did not answer - is it running? (trinity-recsrv status)" >&2; exit 1; }
    echo "Pairing code (valid 24 h, used once): $(cat "$D/pair-code.txt")"
    echo "TRINITY -> Service desk -> Session recordings -> Recording server: address https://$(hostname -f):$(port) + this code"
    ;;
  check)
    [ "$(curl -sk -o /dev/null -w '%{http_code}' --max-time 5 "https://127.0.0.1:$(port)/healthz")" = 200 ];;
  logs) journalctl -u trinity-recsrv --no-pager -n "${2:-100}";;
  store) python3 -c 'import json,sys; d=json.load(open("/etc/trinity-recsrv/trinity.json")); print(d.get("appSettings",{}).get("RecSrvStore","/var/lib/trinity-recsrv/App_Data/recsrv/store"))'; df -h "$("$0" store 2>/dev/null | head -n1)" 2>/dev/null || true;;
  update-access) shift; exec /usr/local/sbin/trinity-node-update access "$@";;
  version) cat /opt/trinity-recsrv/VERSION 2>/dev/null || echo "package=unknown (installed before 0.12.5)";;
  *) echo "usage: trinity-recsrv status | code | logs [n] | store | check | update-access | version" >&2; exit 2;;
esac
