#!/usr/bin/env bash
# WiFi security auditor — scan nearby networks and check security posture.
# Usage: sudo bash scripts/wifi_audit.sh [--interface wlan0]
set -euo pipefail

IFACE="${1:-wlan0}"

echo "=== WiFi Security Audit ==="
echo "Interface: $IFACE"
echo ""

# Check interface exists
if ! ip link show "$IFACE" &>/dev/null; then
  echo "ERROR: Interface $IFACE not found"
  echo "Available wireless interfaces:"
  iw dev 2>/dev/null | grep Interface || echo "  None found"
  exit 1
fi

echo "--- Nearby Networks ---"
if command -v nmcli &>/dev/null; then
  nmcli dev wifi list ifname "$IFACE" 2>/dev/null | while IFS= read -r line; do
    if echo "$line" | grep -qi "WEP"; then
      echo "  🔴 $line"
    elif echo "$line" | grep -qi "OPEN\|--"; then
      echo "  ⚠️  $line"
    else
      echo "  $line"
    fi
  done
elif command -v iwlist &>/dev/null; then
  iwlist "$IFACE" scan 2>/dev/null | grep -E "ESSID|Encryption|Quality|IEEE" | head -40
fi

echo ""
echo "--- Current Connection ---"
iwconfig "$IFACE" 2>/dev/null || echo "  Not connected"

echo ""
echo "--- Security Recommendations ---"
echo "  1. Use WPA3-SAE where available (fallback: WPA2-PSK with AES)"
echo "  2. Disable WPS on all access points"
echo "  3. Use 802.1X/EAP for enterprise networks"
echo "  4. Enable Management Frame Protection (802.11w)"
echo "  5. Segment IoT devices on a separate VLAN/SSID"
