#!/usr/bin/env bash
set -euo pipefail
port() { sed -n 's/^Environment=WSP_HTTPS_PORT=//p' /etc/systemd/system/trinity-connsrv.service | head -n1; }
case "${1:-status}" in
  status)
    systemctl --no-pager --lines=0 status trinity-connsrv || true
    curl -sk --max-time 5 "https://127.0.0.1:$(port)/healthz" || echo "(not answering on port $(port))"; echo
    [ -r /etc/trinity-connsrv/tls.crt ] && echo "Certificate SHA-256: $(openssl x509 -in /etc/trinity-connsrv/tls.crt -outform DER 2>/dev/null | sha256sum | cut -d' ' -f1)"
    for f in /run/trinity-cluster/*.state; do [ -f "$f" ] && echo "VIP (keepalived $(basename "$f" .state)): $(cat "$f")"; done
    echo "guacd: $(systemctl is-active guacd 2>/dev/null || true) (127.0.0.1:4822)"
    if [ -d /var/lib/guacamole/recordings ]; then echo "Local recordings: $(find /var/lib/guacamole/recordings -type f -name 'wsp-*' 2>/dev/null | wc -l) file(s) in /var/lib/guacamole/recordings"; fi
    ;;
  check)
    [ "$(curl -sk -o /dev/null -w '%{http_code}' --max-time 5 "https://127.0.0.1:$(port)/healthz")" = 200 ];;
  logs) journalctl -u trinity-connsrv --no-pager -n "${2:-100}";;
  update-access) shift; exec /usr/local/sbin/trinity-node-update access "$@";;
  version) cat /opt/trinity-connsrv/VERSION 2>/dev/null || echo "package=unknown (installed before 0.12.5)";;
  *) echo "usage: trinity-connsrv status | check | logs [n] | update-access | version" >&2; exit 2;;
esac
