#!/bin/sh


IPADDR=$1
SSID=$2
PASSWORD=$3

usage() {
    echo "Usage: $0 <IPADDR> <SSID> <PASSWORD> "
    exit 1
}

if [ $# -lt 2 ]; then
    usage
fi

uci -q batch <<-EOF >/dev/null
    delete network.guest
    set network.guest=interface
    set network.guest.type=bridge
    set network.guest.proto=static
    set network.guest.ipaddr=$IPADDR
    set network.guest.netmask="255.255.255.0"
EOF
uci commit network

uci -q batch <<-EOF >/dev/null
    delete wireless.guest
    set wireless.guest=wifi-iface
    set wireless.guest.device=ra0
    set wireless.guest.network=guest
    set wireless.guest.mode=ap
    set wireless.guest.ssid=$SSID   
    set wireless.guest.encryption=none

    set wireless.guest_5g=wifi-iface
    set wireless.guest_5g.device=rax0
    set wireless.guest_5g.network=guest
    set wireless.guest_5g.mode=ap
    set wireless.guest_5g.ssid=$SSID   
    set wireless.guest_5g.encryption=none
EOF

[ -n "$PASSWORD" ] && {
    uci set wireless.guest.encryption=psk2
    uci set wireless.guest.key=$PASSWORD
    uci set wireless.guest_5g.encryption=psk2
    uci set wireless.guest_5g.key=$PASSWORD
}

uci commit wireless


uci -q batch <<-EOF >/dev/null
    delete dhcp.guest
    set dhcp.guest=dhcp
    set dhcp.guest.interface=guest
    set dhcp.guest.start=100
    set dhcp.guest.limit=150
    set dhcp.guest.leasetime=2h
EOF
uci commit dhcp

uci -q batch <<-EOF >/dev/null
    delete firewall.guest
    set firewall.guest=zone
    set firewall.guest.name=guest
    set firewall.guest.network=guest
    set firewall.guest.input=REJECT
    set firewall.guest.forward=ACCEPT
    set firewall.guest.output=ACCEPT

    set firewall.guest_forwarding=forwarding
    set firewall.guest_forwarding.src=guest
    set firewall.guest_forwarding.dest=wan    
EOF
uci commit firewall

wifi up