#!/usr/bin/env bash
# Disable autoconnect on stale Wi-Fi profiles (POG-CC, old "preconfigured", phone
# hotspots) so a Pi stops racing between radios and stops asking for credentials
# that no headless box can answer.
#
# Keep-list model: every saved Wi-Fi profile that is NOT kept gets
# connection.autoconnect=no. Nothing is deleted, so rollback is one nmcli away.
#
# Lockout guard: the connection carrying this SSH session is always kept, even if
# it was not named with --keep. On a dual-radio box that means the radio you are
# actually talking over survives, and the other one is what gets pruned.
#
# Secrets are never read or printed — only connection.autoconnect is touched.
#
#   bash prune_wifi_profiles.sh --dry-run
#   bash prune_wifi_profiles.sh --keep DT-2670-18-5
#   bash prune_wifi_profiles.sh --keep DT-2670-18-5 --down
#
# Used by apply_wifi_prune.ps1 (SCP + remote bash).

set -euo pipefail

KEEP=()
DRY_RUN=0
BRING_DOWN=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --keep)
      [[ $# -ge 2 ]] || { echo "FATAL: --keep needs a value" >&2; exit 2; }
      KEEP+=("$2")
      shift 2
      ;;
    --dry-run) DRY_RUN=1; shift ;;
    --down)    BRING_DOWN=1; shift ;;
    -h|--help) sed -n '2,20p' "$0"; exit 0 ;;
    *) echo "FATAL: unknown arg $1" >&2; exit 2 ;;
  esac
done

if ! command -v nmcli >/dev/null 2>&1; then
  echo "FATAL: nmcli not present" >&2
  exit 1
fi

# --- lockout guard: never prune the profile carrying this SSH session ----------
ssh_con=""
if [[ -n "${SSH_CONNECTION:-}" ]]; then
  # SSH_CONNECTION = "<client ip> <client port> <server ip> <server port>"
  read -r _cip _cport sip _sport <<<"${SSH_CONNECTION}"
  ssh_dev="$(ip -o -4 addr show 2>/dev/null \
    | awk -v ip="${sip}" '$4 ~ "^"ip"/" {print $2; exit}')"
  if [[ -n "${ssh_dev}" ]]; then
    ssh_con="$(nmcli -t -f NAME,DEVICE connection show --active 2>/dev/null \
      | awk -F: -v d="${ssh_dev}" '$NF==d {NF--; print; exit}' OFS=:)"
  fi
fi

is_kept() {
  local name="$1"
  [[ -n "${ssh_con}" && "${name}" == "${ssh_con}" ]] && return 0
  local k
  for k in ${KEEP+"${KEEP[@]}"}; do
    [[ "${name}" == "${k}" ]] && return 0
  done
  # Also match on SSID, since profile name and SSID drift apart (the "preconfigured"
  # profile on these Pis carries SSID DT-2670-18-2.4).
  local ssid
  ssid="$(nmcli -g 802-11-wireless.ssid connection show "${name}" 2>/dev/null || true)"
  for k in ${KEEP+"${KEEP[@]}"}; do
    [[ -n "${ssid}" && "${ssid}" == "${k}" ]] && return 0
  done
  return 1
}

echo "host=$(hostname -s)"
[[ -n "${ssh_con}" ]] && echo "ssh_via=${ssh_con} (protected)" || echo "ssh_via=unknown"

disabled=0
kept=0
already=0

while IFS= read -r line; do
  [[ -z "${line}" ]] && continue
  # Parse from the right: NAME may contain colons, TYPE/AUTOCONNECT never do.
  auto="${line##*:}"
  rest="${line%:*}"
  type="${rest##*:}"
  name="${rest%:*}"
  name="${name//\\:/:}"

  [[ "${type}" == "802-11-wireless" ]] || continue

  ssid="$(nmcli -g 802-11-wireless.ssid connection show "${name}" 2>/dev/null || true)"
  label="${name}"
  [[ -n "${ssid}" && "${ssid}" != "${name}" ]] && label="${name} (ssid ${ssid})"

  if is_kept "${name}"; then
    kept=$((kept + 1))
    echo "  KEEP    ${label}"
    continue
  fi

  if [[ "${auto}" != "yes" ]]; then
    already=$((already + 1))
    echo "  ALREADY ${label} autoconnect already off"
    continue
  fi

  if [[ "${DRY_RUN}" == "1" ]]; then
    echo "  WOULD   ${label} autoconnect yes -> no"
    disabled=$((disabled + 1))
    continue
  fi

  if sudo nmcli connection modify "${name}" connection.autoconnect no 2>/dev/null; then
    disabled=$((disabled + 1))
    echo "  DISABLE ${label} autoconnect yes -> no"
    if [[ "${BRING_DOWN}" == "1" ]]; then
      if nmcli -t -f NAME connection show --active 2>/dev/null | grep -qxF "${name}"; then
        sudo nmcli connection down "${name}" >/dev/null 2>&1 \
          && echo "  DOWN    ${label}" \
          || echo "  WARN    ${label} down failed"
      fi
    fi
  else
    echo "  FAIL    ${label} could not modify"
  fi
done < <(nmcli -t -f NAME,TYPE,AUTOCONNECT connection show 2>/dev/null)

echo "active now:"
nmcli -t -f NAME,TYPE,DEVICE connection show --active 2>/dev/null | sed 's/^/  /'

if [[ "${DRY_RUN}" == "1" ]]; then
  echo "PRUNE_RESULT dry_run=1 would_disable=${disabled} kept=${kept} already_off=${already}"
else
  echo "PRUNE_RESULT disabled=${disabled} kept=${kept} already_off=${already}"
fi
