#!/usr/bin/env bash
set -euo pipefail
port="$(sed -n 's/^Environment=WSP_HTTPS_PORT=//p' /etc/systemd/system/trinity-vdigw.service 2>/dev/null || true)"; port="${port:-${WSP_HTTPS_PORT:-443}}"
st() { curl -sk -m 5 "https://127.0.0.1:${port}/vdigw-status"; }
case "${1:-status}" in
  status)
    st | python3 -c '
import json, sys
d = json.load(sys.stdin)
print("role        : %s%s" % (d.get("nodeRole"), " (holds the VIP %s)" % d.get("vip") if d.get("vipHeld") and d.get("vip") else ""))
print("keepalived  : %s   peer %s" % (d.get("keepalived") or "-", d.get("peer") or "-"))
print("paired      : %s  %s  (%s)" % (d.get("paired"), d.get("portal"), d.get("name")))
print("key         : %s   portal certificate %s" % (d.get("keyFingerprint"), d.get("portalCertificate")))
print("shared state: ready %s, version %s, last sync %s" % (d.get("stateReady"), d.get("stateVersion"), d.get("lastSync")))
print("channel     : last ok %s, failures in a row %s %s" % (d.get("lastOk"), d.get("channelFails"), d.get("lastError") or ""))
print("certificate : %s   AD: %s" % (d.get("certFp"), d.get("ad") or "-"))'
    systemctl is-active --quiet keepalived 2>/dev/null && ip -4 -o addr 2>/dev/null | grep -q " $(python3 -c 'import json;print(json.load(open("/etc/trinity-vdigw/trinity.json"))["appSettings"].get("VdiGwVip","-").split("/")[0])' 2>/dev/null)/" && echo "VIP         : on this node" || true ;;
  check)
    if systemctl cat trinity-vdigw >/dev/null 2>&1; then systemctl is-active --quiet trinity-vdigw || exit 1; fi
    max="$(python3 -c 'import json;print(json.load(open("/etc/trinity-vdigw/trinity.json"))["appSettings"].get("VdiGwCheckFails","3"))' 2>/dev/null || echo 3)"
    st | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if d.get('paired') and int(d.get('channelFails') or 0) < int('$max') else 1)" ;;
  failover)
    [ "$(id -u)" = 0 ] || { echo "run as root" >&2; exit 1; }
    secs="${2:-30}"; [[ "$secs" =~ ^[0-9]{1,4}$ ]] || { echo "usage: trinity-vdigw failover [seconds]" >&2; exit 2; }
    st | grep -q '"nodeRole":"active"' || { echo "this node is not the active node - run it on the active one" >&2; exit 1; }
    echo "stopping keepalived for $secs s - the standby takes over the VIP"
    systemctl stop keepalived; sleep "$secs"; systemctl start keepalived
    "$0" status ;;
  pair)
    [ "$(id -u)" = 0 ] || { echo "run as root" >&2; exit 1; }
    [[ "${2:-}" =~ ^[A-Za-z0-9-]{12,40}$ ]] || { echo "usage: trinity-vdigw pair <CODE>" >&2; exit 2; }
    python3 - /etc/trinity-vdigw/trinity.json "$2" <<'PY'
import json, sys
p, code = sys.argv[1:]; d = json.load(open(p, encoding='utf-8-sig')); d.setdefault("appSettings", {})["VdiGwPairCode"] = code
json.dump(d, open(p, 'w', encoding='utf-8'), indent=2)
PY
    rm -f /var/lib/trinity-vdigw/App_Data/vdigw-pair.json; systemctl restart trinity-vdigw; sleep 5; "$0" status ;;
  logs) journalctl -u trinity-vdigw -u keepalived -n 200 --no-pager ;;
  update-access) shift; exec /usr/local/sbin/trinity-node-update access "$@";;
  version) cat /opt/trinity-vdigw/VERSION 2>/dev/null || echo "package=unknown (installed before 0.12.5)";;
  *) cat <<'TRINITY_USAGE'; exit 2 ;;
  trinity-vdigw status            role (active / standby), VIP, keepalived + peer, pairing, key fingerprint, shared state
  trinity-vdigw check             health for the keepalived track script (exit 0 = healthy)
  trinity-vdigw failover [s]      planned switch-over: on the ACTIVE node keepalived stops for s seconds (default 30) -
  trinity-vdigw pair <CODE>       pair again with a new code from TRINITY (VDI & end users -> VDI portal settings -> Gateway clusters)
  trinity-vdigw logs              the service log (journalctl)
Documentation: https://mobileworkplaceservices.ro/docs.html
TRINITY_USAGE
esac
