#!/bin/bash
set -euo pipefail
IFACE="${1:?interface}"

HOTSPOT_WAS_ACTIVE=0

scan_with_nmcli() {
  local iface="$1"
  /usr/bin/nmcli device set "$iface" managed yes >/dev/null 2>&1 || true
  /usr/bin/nmcli dev wifi rescan ifname "$iface" 2>/dev/null || true
  sleep 4
  /usr/bin/nmcli -t -f SSID,SIGNAL,SECURITY dev wifi list ifname "$iface" --rescan no 2>/dev/null || true
}

scan_with_iw_ap_force() {
  local iface="$1"
  if [ ! -x /usr/sbin/iw ]; then
    return 0
  fi

  /usr/sbin/iw dev "$iface" scan ap-force 2>/dev/null | awk '
    function emit() {
      if (ssid == "") return
      signal_pct = int((signal_dbm + 100) * 2)
      if (signal_pct < 0) signal_pct = 0
      if (signal_pct > 100) signal_pct = 100
      gsub(/\t/, " ", ssid)
      print ssid "\t" signal_pct "\t" (secure ? "Secured" : "Open")
    }
    /^BSS / {
      emit()
      ssid = ""
      signal_dbm = -100
      secure = 0
      next
    }
    /^[ \t]*SSID: / {
      ssid = substr($0, index($0, "SSID: ") + 6)
      next
    }
    /^[ \t]*signal: / {
      signal_dbm = $2 + 0
      next
    }
    /^[ \t]*(RSN:|WPA:)/ {
      secure = 1
      next
    }
    END {
      emit()
    }
  ' || true
}

restore_hotspot() {
  if [ "$HOTSPOT_WAS_ACTIVE" -eq 1 ]; then
    /usr/bin/nmcli connection up Hotspot >/dev/null 2>&1 || true
  fi
}

trap restore_hotspot EXIT

if /usr/bin/nmcli -t -f NAME,DEVICE connection show --active 2>/dev/null | grep -Fxq "Hotspot:$IFACE"; then
  HOTSPOT_WAS_ACTIVE=1
  /usr/bin/nmcli connection down Hotspot >/dev/null 2>&1 || true
  sleep 2
fi

SCAN_OUTPUT="$(scan_with_nmcli "$IFACE")"
if [ -n "$SCAN_OUTPUT" ]; then
  printf '%s\n' "$SCAN_OUTPUT"
  exit 0
fi

scan_with_iw_ap_force "$IFACE"
