#!/bin/sh
set -eu

interface_name="${1:-wg-vimify}"
case "$interface_name" in
  *[!a-zA-Z0-9_.-]*|'') echo "Invalid WireGuard interface name." >&2; exit 1 ;;
esac

runtime_dir="/run/vimify-vpn"
output_file="$runtime_dir/status.json"
install -d -m 0755 "$runtime_dir"

last_handshake_at=""
endpoint=""
if command -v wg >/dev/null 2>&1 && wg show "$interface_name" >/dev/null 2>&1; then
  latest_epoch="$(wg show "$interface_name" latest-handshakes | awk 'BEGIN { latest = 0 } $2 > latest { latest = $2 } END { print latest }')"
  endpoint="$(wg show "$interface_name" endpoints | awk 'NR == 1 { print $2 }' | tr -cd 'a-zA-Z0-9._:[]-')"
  if [ "${latest_epoch:-0}" -gt 0 ] 2>/dev/null; then
    last_handshake_at="$(date -u -d "@$latest_epoch" '+%Y-%m-%dT%H:%M:%SZ')"
  fi
fi

temporary_file="$(mktemp "$runtime_dir/.status.XXXXXX")"
if [ -n "$last_handshake_at" ]; then
  printf '{"lastHandshakeAt":"%s","endpoint":"%s"}\n' "$last_handshake_at" "$endpoint" > "$temporary_file"
else
  printf '{"lastHandshakeAt":null,"endpoint":"%s"}\n' "$endpoint" > "$temporary_file"
fi
chmod 0644 "$temporary_file"
mv -f "$temporary_file" "$output_file"
