#!/bin/sh
set -eux

systemctl stop firewalld

# tell NM to ignore router interface and BSS interfaces
mkdir -p /run/udev/rules.d/
echo 'ENV{INTERFACE}=="wlan0*", ENV{NM_UNMANAGED}="1"' > /run/udev/rules.d/99-nm-wifi-test.rules
udevadm control --reload

# start fake wifi wlan0/1 pair and wait for it
modprobe mac80211_hwsim
while ! [ -e /sys/class/net/wlan0 ]; do sleep 0.1; done
# clean up at exit
trap "set +e; pkill hostapd; rmmod mac80211_hwsim" EXIT INT QUIT PIPE

# give router an IP
ip a add 10.0.42.1/24 dev wlan0

# start hostapd with multiple SSIDs (multi-BSS)
cat <<EOF > /tmp/hostapd.conf
interface=wlan0
hw_mode=g
channel=1

# First network - WPA2-PSK
ssid=ZE WIFI!
wpa=2
wpa_passphrase=12345678

# Second network - WPA2-PSK
bss=wlan0_0
ssid=PrivateNet
wpa=2
wpa_passphrase=secret123

# Third network - Open
bss=wlan0_1
ssid=OpenNet
EOF
hostapd -B -i wlan0 /tmp/hostapd.conf

# start DNS server
dnsmasq --keep-in-foreground --log-queries --log-facility=- \
      --conf-file=/dev/null --dhcp-leasefile=/tmp/leases \
      --bind-interfaces --interface=wlan0 --except-interface=lo \
      --dhcp-range=10.0.42.10,10.0.42.200
