#!/bin/bash

set -euo pipefail

echo "Switching to client mode..."

if command -v nmcli > /dev/null 2>&1 && nmcli connection show MPVJ-AP > /dev/null 2>&1; then
	nmcli connection down MPVJ-AP 2>/dev/null || true
	nmcli device set wlan0 autoconnect yes || true
	nmcli device connect wlan0 2>/dev/null || true
else
	systemctl stop mpvj-ap-mode.service 2>/dev/null || true
	systemctl stop hostapd.service dnsmasq.service
	ip addr flush dev wlan0 || true
	ip link set wlan0 up || true
	systemctl start wpa_supplicant.service || systemctl start wpa_supplicant@wlan0.service
fi

echo "Client mode active. wlan0 returned to wpa_supplicant."
