#!/bin/bash

set -euo pipefail

echo "Switching to AP mode..."

rfkill unblock wlan || true

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

echo "AP mode active on wlan0 at 192.168.4.1"
