#!/bin/bash

# TSBINARY=$(which tailscale || echo "tailscale")
TSBINARY='/Applications/Tailscale.app/Contents/MacOS/Tailscale'
VERBOSE=0

# Check for -v argument
while getopts "v" option; do
    case $option in
        v)
            VERBOSE=1
            ;;
    esac
done

# Function to get exit node details
get_exit_node_details() {
    if [[ $VERBOSE -eq 1 ]]; then
        echo "$($TSBINARY exit-node list | awk '/'"$1"'/ {print $4", "$3" ("$2")"}')"
    fi
}

if [[ $VERBOSE -eq 1 ]]; then
    # Get the current exit node details and public IP
    CURRENT_NODE=$(get_exit_node_details 'selected')
    CURRENT_IP=$(curl -s ifconfig.me)
    DNS_SERVER=$(python3 ~/.dns-info.py)

    # Print the current node and IP
    echo "IP address: $CURRENT_IP"
    echo "DNS server: $DNS_SERVER"
    echo "Exit node: ${CURRENT_NODE:-None}"
    echo ""
fi

# Select a new exit node
SELECTED_NODE=$($TSBINARY exit-node list | grep -v -f ~/.vpnblacklist | awk 'BEGIN {srand()} {print rand() " " $0}' | sort -k1,1n | cut -d ' ' -f2- | awk '{print $2}' | head -n 1)

# Set the selected node as the exit node
$TSBINARY set --exit-node="$SELECTED_NODE"

if [[ $VERBOSE -eq 1 ]]; then
    # Wait for the network to update
    sleep 1

    # Get the new public IP
    NEW_IP=$(curl -s ifconfig.me)

    # Get the new exit node details
    NEW_NODE=$(get_exit_node_details "$SELECTED_NODE")

    NEW_DNS=$(python3 ~/.dns-info.py)

    # Print the new node and IP
    echo "New Public IP address: $NEW_IP"
    echo "New DNS server: $NEW_DNS"
    echo "Exit node: ${NEW_NODE:-None}"
    echo ""
fi