#!/bin/bash
# proxy-toggle — root helper. Points macOS system SOCKS proxy at the local
# tunnel, or clears it. Installed root:wheel; the sudoers rule allows only
# the verbs on|off|status for admin accounts.
set -u
PORT="${VLESS_PORT:-1080}"
HOST=127.0.0.1

services() {
    networksetup -listallnetworkservices 2>/dev/null | tail -n +2 | sed 's/^\*//'
}

case "${1:-}" in
  on)
    services | while IFS= read -r s; do
        [ -n "$s" ] || continue
        networksetup -setsocksfirewallproxy "$s" "$HOST" "$PORT" >/dev/null 2>&1
        networksetup -setsocksfirewallproxystate "$s" on >/dev/null 2>&1
    done
    echo "PROXY ON -> $HOST:$PORT (all services)"
    ;;
  off)
    # clear on every service, enabled or not, so nothing can blackhole traffic
    services | while IFS= read -r s; do
        [ -n "$s" ] || continue
        networksetup -setsocksfirewallproxystate "$s" off >/dev/null 2>&1
    done
    echo "PROXY OFF (all services)"
    ;;
  status)
    scutil --proxy | grep -i -E "SOCKS" || echo "no socks proxy set"
    ;;
  *)
    echo "usage: proxy-toggle on|off|status" >&2
    exit 1
    ;;
esac
