#!/bin/sh

case "$1" in
disable)
	uci set fbwifi.main.enabled=0

	uci delete firewall.fbwifi

	uci delete uhttpd.fbwifi_redirect

	uci delete uhttpd.main.json_script
	uci set uhttpd.main.cert='/etc/uhttpd.crt'
	uci set uhttpd.main.key='/etc/uhttpd.key'
	uci set uhttpd.main.rfc1918_filter=1
	;;
enable)
	uci set fbwifi.main.enabled=1

	uci set firewall.fbwifi=include
	uci set firewall.fbwifi.enabled=1
	uci set firewall.fbwifi.family=ipv4
	uci set firewall.fbwifi.path=/usr/share/fbwifi/firewall.include
	uci set firewall.fbwifi.reload=1
	uci set firewall.fbwifi.type=script

	uci set uhttpd.fbwifi_redirect=uhttpd
	uci set uhttpd.fbwifi_redirect.enabled=1
	uci set uhttpd.fbwifi_redirect.cert='/tmp/fbwifi/https_server_cert'
	uci set uhttpd.fbwifi_redirect.home='/dev/null'
	uci set uhttpd.fbwifi_redirect.json_script='/tmp/fbwifi/uhttpd-redirect.json'
	uci set uhttpd.fbwifi_redirect.key='/tmp/fbwifi/https_server_key'
	uci set uhttpd.fbwifi_redirect.listen_http='0.0.0.0:2060'
	uci set uhttpd.fbwifi_redirect.listen_https='0.0.0.0:2061'

	uci set uhttpd.main.cert='/tmp/fbwifi/https_server_cert'
	uci set uhttpd.main.json_script='/usr/share/fbwifi/uhttpd.json'
	uci set uhttpd.main.key='/tmp/fbwifi/https_server_key'
	uci set uhttpd.main.rfc1918_filter=0
	;;
reload)
	/usr/sbin/fbwifi_get_config

	login_url=$(uci -c /var/state get fbwifi.main.captive_portal_url)
	[ -z "$login_url" ] && {
		logger -t fbwifi "captive_portal_url not available yet"
		exit 1
	}
	printf '{ "request": [ ["redirect", "%s", 302] ] }' "$login_url" > /tmp/fbwifi/uhttpd-redirect.json

	/etc/init.d/uhttpd restart

	exit 0
	;;
esac

uci commit
/etc/init.d/uhttpd restart
reload_config
