#!/bin/sh
ssid=$(fw_printenv -n wlanssid || echo OpenIPC)
pass=$(fw_printenv -n wlanpass || echo 12345678)
chan=$(fw_printenv -n wlanchan || echo 1)
[ "$chan" -le 13 ] && mode=g || mode=a

set_config() {
cat << EOF > /tmp/hostapd.conf
ctrl_interface=/var/run/hostapd
interface=wlan0
channel=$chan
hw_mode=$mode
ieee80211n=1
ieee80211ac=1
wmm_enabled=1
rsn_pairwise=CCMP
wpa=2
ssid=$ssid
wpa_passphrase=$pass
EOF
}

case "$1" in
	setup)
		for card in $(lsusb | awk '{print $6}' | uniq); do
			case "$card" in
				"0bda:8812" | "0bda:881a" | "0b05:17d2" | "2357:0101" | "2604:0012")
					driver=88XXau
					;;

				"0bda:a81a")
					driver=8812eu
					;;

				"0bda:f72b" | "0bda:b733")
					driver=8733bu
					;;
			esac
		done

		if [ -z "$driver" ]; then
			echo "Wireless module not detected!"
			exit 1
		fi

		echo "Detected driver: $driver"
		modprobe "$driver" rtw_tx_pwr_by_rate=0 rtw_tx_pwr_lmt_enable=0

		[ "$chan" -le 13 ] && rate=0x8D || rate=0xB7
		echo "$rate" > $(ls /proc/net/*/wlan0/rate_ctl)
		;;

	start)
		set_config
		hostapd /tmp/hostapd.conf -B
		udhcpd -S
		;;

	stop)
		killall -q udhcpd wpa_supplicant
		;;

	*)
		echo "Usage: $0 {setup|start|stop}"
		exit 1
		;;
esac
