#!/usr/bin/env bash
# vpn-proxy-toggle.sh

VM_USER="nate"
VM_IP="192.168.122.241"
SOCKS_PORT=1080
PID_FILE="/tmp/vpn-socks.pid"

start_proxy() {
    # Check if already running
    if pgrep -f "ssh -D $SOCKS_PORT" > /dev/null; then
        echo "Proxy already running"
        return 1
    fi

    ssh -D $SOCKS_PORT -f -N $VM_USER@$VM_IP

    # Get the PID of the SSH process we just started
    sleep 0.5
    pgrep -f "ssh -D $SOCKS_PORT" > "$PID_FILE"

    # Configure system proxy
    gsettings set org.gnome.system.proxy mode 'manual'
    gsettings set org.gnome.system.proxy.socks host 'localhost'
    gsettings set org.gnome.system.proxy.socks port $SOCKS_PORT

    echo "VPN proxy started on localhost:$SOCKS_PORT"
}

stop_proxy() {
    if ! pgrep -f "ssh -D $SOCKS_PORT" > /dev/null; then
        echo "Proxy not running"
        return 1
    fi

    # Find and kill SSH process
    pkill -f "ssh -D $SOCKS_PORT"
    rm -f "$PID_FILE"

    # Disable system proxy
    gsettings set org.gnome.system.proxy mode 'none'

    echo "VPN proxy stopped"
}

case "$1" in
    start)
        start_proxy
        ;;
    stop)
        stop_proxy
        ;;
    restart)
        stop_proxy
        start_proxy
        ;;
    status)
        if pgrep -f "ssh -D $SOCKS_PORT" > /dev/null; then
            echo "Proxy running on localhost:$SOCKS_PORT"
        else
            echo "Proxy not running"
        fi
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac
