#!/usr/bin/env bash
# ── Pi Multi-FX Pedal — WiFi Access Point Setup ────────────────────
# Enables the Pi to act as its own WiFi hotspot.
# Phone connects to "Pi-Pedal" → web UI at http://pedal.local:8080
# No venue WiFi or internet required.
#
# Usage:
#   sudo bash scripts/setup-wifi-ap.sh          # Interactive mode
#   sudo bash scripts/setup-wifi-ap.sh --ssid "Pi-Pedal" --psk "changeme"  # Headless
#   sudo bash scripts/setup-wifi-ap.sh --disable  # Turn off hotspot, back to client mode
#
# After setup:
#   Phone WiFi → join "Pi-Pedal" (password: changeme or your custom psk)
#   Browser → http://pedal.local:8080
#
# Dual WiFi option (for internet while hotspot is active):
#   Plug a USB WiFi dongle. The built-in WiFi becomes the hotspot,
#   the dongle handles internet access. No config changes needed.
# ────────────────────────────────────────────────────────────────────

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

# ── Defaults ──────────────────────────────────────────────────────────
SSID="Pi-Pedal"
PSK="pedal1234"
AP_IP="192.168.4.1"
DISABLE=false

# ── Parse args ────────────────────────────────────────────────────────
while [[ $# -gt 0 ]]; do
    case "$1" in
        --ssid)     SSID="$2"; shift 2 ;;
        --psk)      PSK="$2"; shift 2 ;;
        --disable)  DISABLE=true; shift ;;
        --help|-h)  echo "Usage: $0 [--ssid <name>] [--psk <password>] [--disable]"; exit 0 ;;
        *)          echo "Unknown option: $1"; exit 1 ;;
    esac
done

# ── Colors ────────────────────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

info()  { echo -e "${CYAN}[INFO]${NC} $1"; }
ok()    { echo -e "${GREEN}[OK]${NC}   $1"; }
warn()  { echo -e "${YELLOW}[WARN]${NC} $1"; }
fail()  { echo -e "${RED}[FAIL]${NC} $1"; }

# ═══════════════════════════════════════════════════════════════════════
# DISABLE MODE
# ═══════════════════════════════════════════════════════════════════════

if [ "$DISABLE" = true ]; then
    echo ""
    info "Disabling WiFi access point..."

    sudo systemctl stop hostapd dnsmasq 2>/dev/null || true
    sudo systemctl disable hostapd dnsmasq 2>/dev/null || true

    # Remove AP config from dhcpcd
    sudo sed -i '/^interface wlan0$/d' /etc/dhcpcd.conf 2>/dev/null || true
    sudo sed -i '/^static ip_address=192\.168\.4\.1\/24$/d' /etc/dhcpcd.conf 2>/dev/null || true
    sudo sed -i '/^nohook wpa_supplicant$/d' /etc/dhcpcd.conf 2>/dev/null || true

    # Restart dhcpcd to pick up client mode
    sudo systemctl restart dhcpcd
    ok "Access point disabled. WiFi is back in client mode."
    echo ""
    echo "To reconnect to your home WiFi, edit /etc/wpa_supplicant/wpa_supplicant.conf"
    echo "or use 'sudo raspi-config' → System → Wireless LAN."
    exit 0
fi

# ═══════════════════════════════════════════════════════════════════════
# INSTALL MODE
# ═══════════════════════════════════════════════════════════════════════

echo ""
echo "╔═══════════════════════════════════════════════╗"
echo "║   Pi Multi-FX Pedal — WiFi Access Point Set   ║"
echo "╚═══════════════════════════════════════════════╝"
echo ""
info "SSID:     $SSID"
info "Password: $PSK"
echo ""

# ── 1. Install packages ─────────────────────────────────────────────

info "Installing hostapd and dnsmasq..."
sudo apt-get update -qq
sudo apt-get install -y -qq hostapd dnsmasq
ok "Packages installed"

# Stop services while we configure (they start enabled on install)
sudo systemctl stop hostapd dnsmasq
sudo systemctl disable hostapd dnsmasq  # We enable explicitly at the end

# ── 2. Configure static IP for wlan0 ────────────────────────────────

info "Configuring static IP for wlan0 ($AP_IP)..."

# Remove any existing AP config from dhcpcd.conf
sudo sed -i '/^interface wlan0$/d' /etc/dhcpcd.conf
sudo sed -i '/^static ip_address=192\.168\.[0-9]*\.[0-9]*\/24$/d' /etc/dhcpcd.conf
sudo sed -i '/^nohook wpa_supplicant$/d' /etc/dhcpcd.conf

cat <<EOF | sudo tee -a /etc/dhcpcd.conf > /dev/null

# Pi Multi-FX Pedal — WiFi Access Point
interface wlan0
static ip_address=$AP_IP/24
nohook wpa_supplicant
EOF

ok "Static IP configured"

# ── 3. Configure DNS/DHCP server (dnsmasq) ─────────────────────────

info "Configuring dnsmasq..."

sudo mv /etc/dnsmasq.conf /etc/dnsmasq.conf.orig 2>/dev/null || true

cat <<EOF | sudo tee /etc/dnsmasq.conf > /dev/null
# Pi Multi-FX Pedal — dnsmasq config for WiFi AP
interface=wlan0
dhcp-range=192.168.4.2,192.168.4.20,255.255.255.0,24h
domain=pedal.local
address=/pedal.local/$AP_IP
no-resolv
server=8.8.8.8
server=8.8.4.4
EOF

ok "dnsmasq configured (DHCP range 192.168.4.2-20)"

# ── 4. Configure access point (hostapd) ─────────────────────────────

info "Configuring hostapd..."

cat <<EOF | sudo tee /etc/hostapd/hostapd.conf > /dev/null
# Pi Multi-FX Pedal — hostapd config
interface=wlan0
ssid=$SSID
hw_mode=g
channel=6
wmm_enabled=0
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=$PSK
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP
EOF

# Point hostapd at our config
if grep -q "^#DAEMON_CONF" /etc/default/hostapd 2>/dev/null; then
    sudo sed -i 's|^#DAEMON_CONF.*|DAEMON_CONF="/etc/hostapd/hostapd.conf"|' /etc/default/hostapd
fi

ok "hostapd configured (SSID: $SSID)"

# ── 5. Enable services ──────────────────────────────────────────────

info "Enabling hostapd and dnsmasq services..."
sudo systemctl unmask hostapd 2>/dev/null || true
sudo systemctl enable hostapd
sudo systemctl enable dnsmasq
ok "Services enabled to start on boot"

# ── 6. Start now ────────────────────────────────────────────────────

info "Starting services..."
sudo systemctl restart dhcpcd
sudo systemctl start dnsmasq
sudo systemctl start hostapd

sleep 2

# Verify
if systemctl is-active --quiet hostapd && systemctl is-active --quiet dnsmasq; then
    ok "WiFi access point is running"
else
    fail "One or more services failed to start. Check:"
    echo "  sudo systemctl status hostapd"
    echo "  sudo systemctl status dnsmasq"
    echo "  sudo journalctl -u hostapd -n 30 --no-pager"
    exit 1
fi

# ═══════════════════════════════════════════════════════════════════════
# DONE
# ═══════════════════════════════════════════════════════════════════════

echo ""
echo "╔═══════════════════════════════════════════════╗"
echo "║   WiFi Access Point Setup Complete 🎸         ║"
echo "╚═══════════════════════════════════════════════╝"
echo ""
echo "  📶 SSID:     $SSID"
echo "  🔑 Password: $PSK"
echo "  🔗 Web UI:   http://pedal.local:8080"
echo "  🌐 IP:       http://$AP_IP:8080"
echo ""
echo "Your phone should see '$SSID' in available WiFi networks."
echo "Join it, then open the browser to the URL above."
echo ""
echo "To disable the hotspot later:"
echo "  sudo bash $0 --disable"
echo ""
echo "Note: The Pi's WiFi is now in AP mode — it won't connect"
echo "to the internet. If you need internet access, plug in a"
echo "USB WiFi dongle (the pedal auto-detects it)."
echo ""