#!/bin/sh

. /lib/functions.sh

check_enabled() {
	config_get enabled "$1" "enabled" "0"
	[ "$enabled" -eq 1 ] && hotspot_enabled=true
}
check_firewall() {
	config_get name "$1" "name"
	[ "$name" = "Hotspot_input" ] && rule_exists=true
}

hotspot_enabled=false
rule_exists=false

config_load "chilli"
config_foreach check_enabled "chilli"

config_load "firewall"
config_foreach check_firewall "rule"

if [ "$hotspot_enabled" = "true" ] && [ "$rule_exists" = "false" ]; then
	uci_add "firewall" "zone" "hotspot"
	uci_set "firewall" "$CONFIG_SECTION" "name" "hotspot"
	uci_set "firewall" "$CONFIG_SECTION" "input" "REJECT"
	uci_set "firewall" "$CONFIG_SECTION" "forward" "REJECT"
	uci_set "firewall" "$CONFIG_SECTION" "device" "tun0 tun1 tun2 tun3"
	uci_set "firewall" "$CONFIG_SECTION" "output" "ACCEPT"

	uci_add "firewall" "forwarding"
	uci_set "firewall" "$CONFIG_SECTION" "src" "hotspot"
	uci_set "firewall" "$CONFIG_SECTION" "dest" "wan"

	uci_add "firewall" "rule"
	uci_set "firewall" "$CONFIG_SECTION" "name" "Hotspot_input"
	uci_set "firewall" "$CONFIG_SECTION" "enabled" "1"
	uci_set "firewall" "$CONFIG_SECTION" "src" "hotspot"
	uci_set "firewall" "$CONFIG_SECTION" "target" "ACCEPT"
	uci_set "firewall" "$CONFIG_SECTION" "proto" "all"
	uci_add_list "firewall" "$CONFIG_SECTION" "dest_port" "53"
	uci_add_list "firewall" "$CONFIG_SECTION" "dest_port" "67"
	uci_add_list "firewall" "$CONFIG_SECTION" "dest_port" "68"
	uci_add_list "firewall" "$CONFIG_SECTION" "dest_port" "444"
	uci_add_list "firewall" "$CONFIG_SECTION" "dest_port" "81"
	uci_add_list "firewall" "$CONFIG_SECTION" "dest_port" "1812"
	uci_add_list "firewall" "$CONFIG_SECTION" "dest_port" "1813"
	uci_add_list "firewall" "$CONFIG_SECTION" "dest_port" "3991"
	uci_add_list "firewall" "$CONFIG_SECTION" "dest_port" "3990"
fi


device=$(uci_get system system devicename)

[ "${device:0:3}" != "TAP" ] && {
	enable=$(uci_get firewall pscan port_scan)

	[ -z "$enable" ] && enable="0"

	uci_batch <<-EOT
		set firewall.pscan=include
		set firewall.pscan.type=script
		set firewall.pscan.reload='1'
		set firewall.pscan.path=/usr/bin/attack_prevention
	EOT
}
uci_commit "firewall"
