#!/usr/bin/env bash
set -euo pipefail

delta_alias="${DELTA_SSH_ALIAS:-dit}"
connect_timeout="${FLEET_CONNECT_TIMEOUT:-8}"
local_host="$(hostname -s 2>/dev/null || hostname)"

section() {
  printf '\n== %s ==\n' "$1"
}

section "Control node"
printf 'host\t%s\n' "$local_host"

section "Tailnet"
tailscale_cli="$(command -v tailscale 2>/dev/null || true)"
if [[ -z "$tailscale_cli" && -x /Applications/Tailscale.app/Contents/MacOS/Tailscale ]]; then
  tailscale_cli="/Applications/Tailscale.app/Contents/MacOS/Tailscale"
fi
if [[ -n "$tailscale_cli" ]]; then
  "$tailscale_cli" status --json | python3 -c '
import json, sys
d = json.load(sys.stdin)
nodes = [d.get("Self", {})] + list(d.get("Peer", {}).values())
for n in sorted(nodes, key=lambda x: x.get("HostName", "")):
    ips = ",".join(n.get("TailscaleIPs", []))
    name = n.get("HostName", "?")
    if name == "localhost" and n.get("DNSName"):
        name = n["DNSName"].split(".", 1)[0]
    print("{}\t{}\t{}\t{}".format(
        name,
        n.get("OS", "?"),
        str(n.get("Online", False)).lower(),
        ips,
    ))
'
else
  printf 'tailscale CLI unavailable\n'
fi

section "Apple developer devices"
if command -v xcrun >/dev/null 2>&1; then
  xcrun devicectl list devices 2>&1 || true
else
  printf 'xcrun unavailable on this control node\n'
fi

run_delta() {
  if [[ "$local_host" == deltaisland* ]]; then
    bash -s
  else
    ssh -o BatchMode=yes -o ConnectTimeout="$connect_timeout" "$delta_alias" 'bash -s'
  fi
}

section "Delta"
if ! run_delta <<'REMOTE'
set -u
printf 'host\t%s\n' "$(hostname -f 2>/dev/null || hostname)"
printf 'uptime\t%s\n' "$(uptime -p 2>/dev/null || true)"
df -h / | awk 'NR == 2 {print "rootfs\t" $2 " total\t" $3 " used\t" $4 " available\t" $5 " used"}'

printf '\n-- failed units --\n'
systemctl --failed --no-pager --plain --no-legend 2>/dev/null || true
systemctl --user --failed --no-pager --plain --no-legend 2>/dev/null || true

printf '\n-- running application user units --\n'
systemctl --user list-units --type=service --state=running --no-pager --plain --no-legend 2>/dev/null \
  | awk '$1 ~ /^(cloudflared|hermes|islandflow|pr-reviewer|signal-cli|syncthing|t3)/ {print}' || true

printf '\n-- compose projects --\n'
docker compose ls --format json 2>/dev/null \
  | python3 -c 'import json,sys; [print("{}\t{}\t{}".format(x.get("Name", "?"), x.get("Status", "?"), x.get("ConfigFiles", "?"))) for x in json.load(sys.stdin)]' || true

printf '\n-- containers --\n'
docker ps --format '{{.Names}}\t{{.State}}\t{{.Status}}\t{{.Ports}}' 2>/dev/null || true

printf '\n-- listeners --\n'
ss -lntH 2>/dev/null || true

printf '\n-- tailscale serve --\n'
tailscale serve status --json 2>/dev/null || true
REMOTE
then
  printf 'Delta unavailable through %s\n' "$delta_alias" >&2
  exit 1
fi
