#!/bin/bash

# Configuration
SSH_USER="connor.johnstone@arcfield.com"
SSH_HOST="localhost"
SSH_PORT="9000"
REMOTE="${SSH_USER}@${SSH_HOST}:${SSH_PORT}"

# Check if sshuttle is already running with this remote
SSHUTTLE_PID=$(pgrep -f "sshuttle.*${REMOTE}")

if [ -n "$SSHUTTLE_PID" ]; then
    # sshuttle is running, so kill it
    echo "sshuttle is running (PID: $SSHUTTLE_PID). Stopping..."
    kill "$SSHUTTLE_PID"

    # Wait a moment and verify it stopped
    sleep 1
    if pgrep -f "sshuttle.*${REMOTE}" > /dev/null; then
        echo "Process didn't stop gracefully, forcing..."
        kill -9 "$SSHUTTLE_PID"
    fi

    echo "sshuttle stopped."
else
    # sshuttle is not running, check SSH connection and start it
    echo "sshuttle is not running. Checking SSH connection..."

    # Test SSH connection (with timeout)
    if ssh -p "$SSH_PORT" -o ConnectTimeout=5 -o BatchMode=yes "$SSH_USER@$SSH_HOST" exit 2>/dev/null; then
        echo "SSH connection successful. Starting sshuttle..."
        sshuttle -r "$REMOTE" --dns 0/0 > /tmp/sshuttle 2>&1 &
        echo "sshuttle started in background (PID: $!)."
    else
        echo "ERROR: Cannot establish SSH connection to $REMOTE"
        echo "Please verify:"
        echo "  1. SSH service is running on $SSH_HOST:$SSH_PORT"
        echo "  2. You have valid SSH credentials/keys configured"
        echo "  3. The host is reachable"
        exit 1
    fi
fi
