#!/bin/sh

IFACE_SECTION=""
PASSWORD_MISSING=1
WPS_DISABLED=1

BOARD_NAME=$(ubus call system board | jsonfilter -e '@.board_name')
case "$BOARD_NAME" in
	routerich,be7200)
		PHY="phy0."
		;;
	*)
		PHY="phy"
		;;
esac

for section in $(uci show wireless | sed -n 's/^\(wireless\.\([^=]*\)\)=wifi-iface$/\2/p'); do
	device=$(uci -q get wireless.$section.device)
	mode=$(uci -q get wireless.$section.mode)
	encryption=$(uci -q get wireless.$section.encryption)
	key=$(uci -q get wireless.$section.key)
	wps=$(uci -q get wireless.$section.wps_pushbutton)

	if [ "$device" = "radio0" ] && [ "$mode" = "ap" ]; then
		if [ -n "$encryption" ] && [ -n "$key" ]; then
			PASSWORD_MISSING=0
		fi
		if [ "$wps" = "1" ]; then
			WPS_DISABLED=0
		fi
		if [ $PASSWORD_MISSING -eq 0 ] && [ $WPS_DISABLED -eq 0 ]; then
			IFACE_SECTION="$section"
			break
		fi
	fi
done

if [ $PASSWORD_MISSING -eq 1 ]; then
	logger -t wps -p daemon.warn "WPS not activated: 2.4GHz Wi-Fi password is missing."
	exit 1
fi

if [ $WPS_DISABLED -eq 1 ]; then
	logger -t wps -p daemon.warn "WPS not activated: WPS pushbutton disabled."
	exit 1
fi

hostapd_cli -i ${PHY}0-ap0 wps_pbc

exit 0