#!/bin/bash
# Toggle between hotspot mode (AP + captive portal) and client mode (WiFi + tailscale)
# Usage: toggle-hotspot.sh [hotspot|client]

set -e

HOTSPOT_SSID="Hermes-Pi-Setup"

start_hotspot() {
    echo "Starting hotspot mode..."
    
    # Disable NetworkManager on wlan0 so it doesn't fight hostapd
    sudo nmcli device set wlan0 managed no 2>/dev/null || true
    
    # Stop client mode
    sudo systemctl stop wpa_supplicant 2>/dev/null || true
    sudo ip addr flush wlan0 2>/dev/null || true
    
    # Set regulatory domain
    sudo iw reg set US 2>/dev/null || true
    
    # Set static IP for hotspot
    sudo ip addr add 192.168.50.1/24 dev wlan0 2>/dev/null || true
    sudo ip link set wlan0 up
    
    # Start hotspot services
    sudo systemctl start hostapd
    sudo systemctl start dnsmasq
    sudo systemctl start hermes-portal
    
    echo "Hotspot '${HOTSPOT_SSID}' is active."
    echo "Connect from your phone, then visit http://192.168.50.1"
}

start_client() {
    echo "Starting client mode..."
    
    # Stop hotspot services
    sudo systemctl stop hermes-portal 2>/dev/null || true
    sudo systemctl stop hostapd 2>/dev/null || true
    sudo systemctl stop dnsmasq 2>/dev/null || true
    
    # Flush hotspot IP
    sudo ip addr flush wlan0 2>/dev/null || true
    
    # Re-enable NetworkManager on wlan0
    sudo nmcli device set wlan0 managed yes 2>/dev/null || true
    
    # Start client mode
    sudo ip link set wlan0 up
    sudo systemctl restart wpa_supplicant 2>/dev/null || true
    sudo systemctl restart NetworkManager 2>/dev/null || true
    sleep 3
    sudo dhcpcd wlan0 2>/dev/null || true
    
    # Start Tailscale
    sudo tailscale up --hostname=hermes-pi 2>/dev/null || true
    
    echo "Client mode active. Waiting for IP..."
    sleep 5
    ip -4 addr show wlan0 2>/dev/null | grep inet
    echo "Tailscale:"
    sudo tailscale ip 2>/dev/null || echo "Tailscale not connected yet"
}

case "${1}" in
    hotspot|ap)
        start_hotspot
        ;;
    client|wifi)
        start_client
        ;;
    *)
        # Toggle: if hotspot is running, switch to client, else switch to hotspot
        if sudo systemctl is-active --quiet hostapd 2>/dev/null; then
            start_client
        else
            start_hotspot
        fi
        ;;
esac
