#!/bin/sh
set -eu

ACTION="${1:-}"
case "$ACTION" in
  probe|up|down|status|cleanup)
    ;;
  *)
    echo "Usage: nordvpn-wireguard-helper.sh [probe|up|down|status|cleanup]" >&2
    exit 2
    ;;
esac

WG_QUICK="/opt/homebrew/bin/wg-quick"
WG="/opt/homebrew/bin/wg"
WG_CONFIG="/Users/stefano/.nordvpn-client/wireguard/nordvpnctl.conf"
WG_INTERFACE="nordvpnctl"
PATH="/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin"
export PATH

if [ "$ACTION" = "probe" ] || [ "$ACTION" = "status" ]; then
  test -x "$WG_QUICK"
  ACTIVE=0
  RUNTIME_INTERFACE=""
  if [ -x "$WG" ]; then
    RUNTIME_INTERFACE=$("$WG" show interfaces 2>/dev/null | awk 'NF { print $1; exit }')
  fi
  if [ -n "$RUNTIME_INTERFACE" ]; then
    ACTIVE=1
  elif [ -x "$WG" ] && "$WG" show "$WG_INTERFACE" >/dev/null 2>&1; then
    ACTIVE=1
  elif /sbin/ifconfig "$WG_INTERFACE" >/dev/null 2>&1; then
    ACTIVE=1
  elif pgrep -f "wg-quick up $WG_CONFIG" >/dev/null 2>&1; then
    ACTIVE=1
  elif pgrep -f "wireguard-go utun" >/dev/null 2>&1; then
    ACTIVE=1
  fi

  echo "active=$ACTIVE"
  echo "interfaceName=$WG_INTERFACE"
  if [ -n "$RUNTIME_INTERFACE" ]; then
    echo "wireguardInterface=$RUNTIME_INTERFACE"
  fi
  if [ -f "$WG_CONFIG" ]; then
    echo "configPath=$WG_CONFIG"
  fi
  exit 0
fi

if [ "$ACTION" = "cleanup" ]; then
  "$WG_QUICK" down "$WG_CONFIG" >/dev/null 2>&1 || true
  exit 0
fi

exec "$WG_QUICK" "$ACTION" "$WG_CONFIG"
