#! /bin/sh

cleanup()
{
    for jid in `jls | awk '{print $1}' | grep -v JID`
    do
        jail -r ${jid}
    done
    zfs destroy -f zroot/jails/j1
    zfs destroy -f zroot/jails/j2
    zfs destroy -f zroot/jails/j3
    for ng in `ngctl list | awk '{print $2}'`
    do
        ngctl shutdown ${ng}:
    done
    for br in `ifconfig -g bridge`
    do
        ifconfig ${br} destroy
    done
    for vlan in `ifconfig -g vlan`
    do
        ifconfig ${vlan} destroy
    done
    for interface in `ifconfig -l`
    do
        if echo ${interface} | grep epair
        then
            ifconfig ${interface} destroy
        fi
    done
}

setup_vlan()
{
    vlan_id=${1}
    ngctl mkpeer hn1vl: eiface hn1vl${vlan_id} ether
    ngctl name hn1vl:hn1vl${vlan_id} hn1vl${vlan_id}
    ngif=`ngctl msg hn1vl:hn1vl${vlan_id} getifname | grep Args | awk '{print $2}' | tr -d '"'`
    ifconfig ${ngif} name hn1vl${vlan_id}
    ngctl msg hn1vl: addfilter "{ vlan=${vlan_id} hook=\"hn1vl${vlan_id}\" }"
    ifconfig hn1vl${vlan_id} up
    ifconfig bridge${vlan_id} create
    ifconfig bridge${vlan_id} name hn1vl${vlan_id}br
    ifconfig hn1vl${vlan_id}br up
    ifconfig hn1vl${vlan_id}br addm hn1vl${vlan_id}
}

create_jail()
{
    jail_no=${1}
    jail_vlan=${2}
    jail_ip=${3}
    jail_subnet=${4}
    jail_gateway=${5}

    jail_name=j${jail_no}
    jail_epair="epair${jail_no}"

    zfs clone zroot/jails/jail@base zroot/jails/${jail_name}
    jail -c path=/jails/${jail_name} mount.devfs host.hostname=${jail_name} jid=${jail_no} persist=true name=${jail_name} vnet
    jexec ${jail_name} sysctl net.inet6.ip6.auto_linklocal=0

    ifconfig ${jail_epair} create
    ifconfig ${jail_epair}a up
    ifconfig hn1vl${jail_vlan}br addm ${jail_epair}a
    ifconfig ${jail_epair}b vnet ${jail_name}
    jexec ${jail_name} ifconfig ${jail_epair}b up

    jexec ${jail_name} ifconfig ${jail_epair}b inet ${jail_ip} netmask ${jail_subnet} up
    jexec ${jail_name} /sbin/route add default ${jail_gateway}
    #jexec ${jail_name} dhclient -b ${jail_epair}b
}


cleanup
kldload ng_ether || true

set -e


# Setup VLANs
ifconfig hn1 up
ngctl mkpeer hn1: vlan lower downstream
ngctl name hn1:lower hn1vl
ngctl connect hn1: hn1vl: upper nomatch

#          vlan-id
setup_vlan 50
setup_vlan 51
setup_vlan 52

#               no  vlanid  ip-address      subnet-mask     gateway
create_jail     1   50      10.30.50.225    255.255.255.0   10.30.50.1
create_jail     2   51      10.30.51.225    255.255.255.0   10.30.51.1
create_jail     3   52      10.30.52.225    255.255.255.0   10.30.52.1

echo done
