#!/usr/bin/env bash # Stop the portal access point and return wlan0 to WiFi client mode. set -euo pipefail CON_NAME="${PORTAL_AP_CON_NAME:-portal-ap}" WLAN_IF="${PORTAL_AP_IF:-wlan0}" if [[ "${EUID}" -ne 0 ]]; then echo "Error: run as root: sudo $0" >&2 exit 1 fi if ! command -v nmcli >/dev/null; then echo "Error: NetworkManager (nmcli) is required" >&2 exit 1 fi if nmcli -t -f NAME connection show | grep -Fxq "${CON_NAME}"; then nmcli connection down "${CON_NAME}" 2>/dev/null || true nmcli connection modify "${CON_NAME}" connection.autoconnect no echo "Access point '${CON_NAME}' stopped (autoconnect disabled)." else echo "Connection '${CON_NAME}' not found." fi rfkill unblock wifi >/dev/null 2>&1 || true nmcli radio wifi on >/dev/null 2>&1 || true nmcli device disconnect "${WLAN_IF}" 2>/dev/null || true nmcli device wifi rescan 2>/dev/null || true sleep 2 # Saved client profiles, newest first (skip the AP connection). mapfile -t CLIENT_CONS < <( nmcli -t -f NAME,TYPE,TIMESTAMP connection show | awk -F: -v ap="${CON_NAME}" ' $2 == "802-11-wireless" && $1 != ap { print $3 "\t" $1 } ' | sort -rn | cut -f2 ) CONNECTED=0 for client_con in "${CLIENT_CONS[@]}"; do key_mgmt="$(nmcli -g 802-11-wireless-security.key-mgmt connection show "${client_con}" 2>/dev/null || true)" if [[ -z "${key_mgmt}" ]]; then echo "Skipping '${client_con}': missing 802-11-wireless-security.key-mgmt." echo " Fix: sudo nmcli connection delete ${client_con}" echo " sudo nmcli device wifi connect password " continue fi if nmcli connection up "${client_con}" ifname "${WLAN_IF}" 2>/dev/null; then echo "wlan0 connected as client: ${client_con}" CONNECTED=1 break fi done if ((CONNECTED == 0)); then echo "wlan0 is in client mode but no saved network connected." echo "List networks: nmcli device wifi list" echo "Connect: sudo nmcli device wifi connect password " fi echo "Remove AP permanently: sudo nmcli connection delete ${CON_NAME}"