#! /bin/sh

# use this script to prepare firewall and dhcp for guest wifi

usage () {
    echo "$0 start <ipaddr> <netmask>"
    echo "$0 stop"
    exit 1
}

start_guest() {
    local ip="$1"
    local mask="$2"
    uci -q batch <<EOF
set network.eth0_3=switch_vlan
set network.eth0_3.device=eth0
set network.eth0_3.vlan=3
set network.eth0_3.ports=5
set network.guest=interface
set network.guest.type=bridge
set network.guest.ifname=eth0.3
set network.guest.proto=static
set network.guest.ipaddr=$ip
set network.guest.netmask=$mask
set dhcp.guest=dhcp
set dhcp.guest.interface=guest
set dhcp.guest.leasetime=12h
set dhcp.guest.force=1
set dhcp.guest.start=5
set dhcp.guest.limit=250
set firewall.guest_zone=zone
set firewall.guest_zone.name=guest
set firewall.guest_zone.network=guest
set firewall.guest_zone.input=REJECT
set firewall.guest_zone.forward=REJECT
set firewall.guest_zone.output=ACCEPT
set firewall.guest_forward=forwarding
set firewall.guest_forward.src=guest
set firewall.guest_forward.dest=wan
set firewall.guest_dns=rule
set firewall.guest_dns.name='Allow Guest DNS Queries'
set firewall.guest_dns.src=guest
set firewall.guest_dns.dest_port=53
set firewall.guest_dns.proto=tcpudp
set firewall.guest_dns.target=ACCEPT
set firewall.guest_dhcp=rule
set firewall.guest_dhcp.name='Allow Guest DHCP request'
set firewall.guest_dhcp.src=guest
set firewall.guest_dhcp.src_port='67-68'
set firewall.guest_dhcp.dest_port='67-68'
set firewall.guest_dhcp.proto='udp'
set firewall.guest_dhcp.target=ACCEPT
set firewall.guest_8999=rule
set firewall.guest_8999.name='Hello wifi 8999'
set firewall.guest_8999.src=guest
set firewall.guest_8999.proto=tcp
set firewall.guest_8999.dest_port=8999
set firewall.guest_8999.target=ACCEPT
set firewall.guest_8300=rule
set firewall.guest_8300.name='Hello wifi 8300'
set firewall.guest_8300.src=guest
set firewall.guest_8300.proto=tcp
set firewall.guest_8300.dest_port=8300
set firewall.guest_8300.target=ACCEPT
set firewall.guest_7080=rule
set firewall.guest_7080.name='Hello wifi 7080'
set firewall.guest_7080.src=guest
set firewall.guest_7080.proto=tcp
set firewall.guest_7080.dest_port=7080
set firewall.guest_7080.target=ACCEPT
commit network
commit dhcp
commit firewall
EOF
/etc/init.d/network restart
/etc/init.d/firewall restart
/etc/init.d/dnsmasq restart
/etc/init.d/trafficd restart
}

stop_guest() {
uci -q batch <<EOF
delete network.eth0_3
delete network.guest
delete dhcp.guest
delete firewall.guest_zone
delete firewall.guest_forward
delete firewall.guest_dns
delete firewall.guest_dhcp
delete firewall.guest_8999
delete firewall.guest_8300
delete firewall.guest_7080
commit network
commit dhcp
commit firewall
EOF
/etc/init.d/network restart
/etc/init.d/firewall restart
/etc/init.d/dnsmasq restart
}

case "$1" in
    start)
	shift
	start_guest "$1" "$2"
    ;;
    stop)
	stop_guest
    ;;
    *)
	usage
    ;;
esac
