iterations=10

create_jails()
{
    kldload pf
    for i in `seq 1 ${iterations}`
    do
        echo "----------"
        echo "Create zfs dataset for jail_${i}"
        zfs clone zroot/jails/12jail@base zroot/jails/jail_${i}
        echo "Create jail_${i}"
        jail -c path=/jails/jail_${i} mount.devfs host.hostname=jail_${i} jid=${i} persist=true name=jail_${i} vnet
        echo "Create epair${i}"
        ifconfig epair${i} create
        ifconfig epair${i}a up
        echo "disable ipv6 in jail"
        jexec jail_${i} sysctl net.inet6.ip6.auto_linklocal=0
        echo "Add epair${i}b to jail_${i}"
        ifconfig epair${i}b vnet jail_${i}
        echo "Configure epair${i}b in jail_${i}"
        jexec jail_${i} ifconfig epair${i}b up
        jexec jail_${i} ifconfig epair${i}b inet 10.10.10.1${i}/24
        jexec jail_${i} route add default 10.10.10.1
        echo "Setup pf in the jail_${i}"
        cat > /jails/jail_${i}/etc/pf.conf << EOF
pass in on epair${i}b from any to any

EOF
        jexec jail_${i} service pf onestart
        jexec jail_${i} pfctl -f /etc/pf.conf
        
        reload_host_pf
    done
}

destroy_jails()
{
    for i in `seq 1 ${iterations}`
    do
        echo "----------"
        echo "Stop pf in jail_${i}"
        jexec jail_${i} service pf onestop
        echo "Destroy epair${i}"
        ifconfig epair${i}a destroy
        echo "Remove jail_${i}"
        jail -r jail_${i}
        echo "Unmount devfs in jail_${i}"
        umount /jails/jail_${i}/dev
        echo "Destroy zfs dataset for jail_${i}"
        zfs destroy -rf zroot/jails/jail_${i}
        
        reload_host_pf
    done
}

cleanup()
{
    echo "cleaning up zfs datasets"
    for i in `seq 1 ${iterations}`
    do
        echo "Destroy zfs dataset for jail_${i}"
        zfs destroy -rf zroot/jails/jail_${i}
    done
}

reload_host_pf()
{
    echo "Reloading pf on the host"
    pfctl -f /etc/pf.conf
    sleep 1
}

run_test()
{
    echo "----------"
    echo "setup pf on host"
    service pf onestart
    cat > /etc/pf.conf << EOF
pass in from any to any

EOF
    reload_host_pf
    echo "----------"
    
    echo "Start jails"
    create_jails
        
    echo "Stop jails"
    destroy_jails
}

cleanup
run_test
