#!/usr/bin/env bash
# Count WireGuard peers and write the counts to the site's JSON.
# Must run as root (wg needs root). See deploy/wg-count.service|timer.
#
#   ./wg_count.sh [interface] [output-json-path]
#   e.g.  ./wg_count.sh wg0 /var/www/html/assets/wireguard.json
#
# A peer is "online" if its last handshake was within HANDSHAKE_WINDOW seconds.
set -euo pipefail

IFACE="${1:-wg0}"
HANDSHAKE_WINDOW=180
# 2nd arg = where to write the JSON. Defaults to the repo's public/assets.
OUT="${2:-$(cd "$(dirname "$0")/.." && pwd)/public/assets/wireguard.json}"

now=$(date +%s)
online=0
total=0

# `wg show <iface> dump`: first line is the interface; peer lines follow.
# peer fields: pubkey psk endpoint allowed-ips latest-handshake rx tx keepalive
while read -r _pub _psk _endpoint _allowed handshake _rx _tx _ka; do
    total=$((total + 1))
    if [ -n "${handshake:-}" ] && [ "$handshake" -gt 0 ] 2>/dev/null; then
        if [ $((now - handshake)) -le "$HANDSHAKE_WINDOW" ]; then
            online=$((online + 1))
        fi
    fi
done < <(wg show "$IFACE" dump | tail -n +2)

printf '{"online":%d,"total":%d,"updated":%d}\n' "$online" "$total" "$now" > "$OUT"
