#!/bin/sh

echo "$0 called with args: $@" > /tmp/multiap.log

# Generate wireless UCI config
if [ -n "$BANDS" ] && [ -n "$OUI" ]; then
	echo "[multiap] Generating wireless config for BAND=$BANDS OUI=$OUI"
	/lib/wifi/wireless.sh "$BANDS" "$OUI"
fi


while [ "$1" != "" ]; do
	case $1 in
		--multiap_mode )
			shift
			multiap_mode=$1
			echo "Case:::: multiap_mode: $multiap_mode" >> /tmp/multiap.log
			;;
		--alid )
			shift
			alid=$1
			case "$alid" in
				*[!0-9a-fA-F:]*)
					echo "ERROR: invalid MAC address for --alid: $alid" >&2
					exit 1 ;;
			esac
			sed -i "s|option.*macaddress.*$|option macaddress '$alid'|" /etc/config/ieee1905
			;;
		* )
			;;
	esac
	shift
done

multiap_mode=${multiap_mode:-full}

case $multiap_mode in
	auto )
		run_cntlr=2
		run_agent=1
		;;
	controller )
		run_agent=0
		run_cntlr=1
		;;
	agent )
		run_agent=1
		run_cntlr=0
		sed -i '/option.*registrar.*$/d' /etc/config/ieee1905
		sed -i "s/option.*local.*$/option local '0'/" /etc/config/mapagent
		;;
	none )
		run_agent=0
		run_cntlr=0
		sed -i '/option.*registrar.*$/d' /etc/config/ieee1905
		;;
	* | full )
		run_agent=1
		run_cntlr=1
		;;
esac

echo "multi_mode = ${multiap_mode}   run_agent = ${run_agent}   run_cntlr = ${run_cntlr} alid = ${alid}" >> /tmp/multiap.log

/sbin/cmdsrv.sh &

ubusd &

for i in $(seq 1 30); do
    if [ -S /var/run/ubus/ubus.sock ]; then
        echo "[init] ubusd socket ready."
        break
    fi
    sleep 1
done

[ ! -S /var/run/ubus/ubus.sock ] && {
    echo "[init] ERROR: /var/run/ubus/ubus.sock not present!"
}

wifimngr &
ieee1905d &
sleep 3
ubus call ieee1905 add_interface '{"ifname":"eth0"}'
sleep 3

ubus list

#if ! ubus list >/dev/null 2>&1; then
#    echo "[init] ERROR: ubus is not responding!"
#fi

[ "$run_agent" -eq 1 ] &&  mapagent -d &
sleep 3

[ "$run_cntlr" -eq 1 ] &&  mapcontroller -d &


#exec bash
wait
