#!/usr/local/bin/bash

cleanup() {
    ngctl shutdown host_link2:
    ngctl shutdown host_uplink0:
    ngctl shutdown host_bridge0:
    ngctl shutdown wg_link2:
    ngctl shutdown wg_uplink0:
    ngctl shutdown wg_bridge0:
}

setup_netgraph_start() {
    cleanup

    ngctl -d -f - <<EOF
mkpeer . eiface hook ether
name .:hook host_uplink0
EOF

    ngctl -d -f - <<EOF
mkpeer host_uplink0: bridge ether link0
name host_uplink0:ether host_bridge0
EOF

    ngctl -d -f - <<EOF
mkpeer host_bridge0: eiface link2 ether
name host_bridge0:link2 host_link2
EOF

    ifconfig $(ngctl msg 'host_uplink0:' getifname | grep Args | cut -d '"' -f 2) name host_uplink0 10.193.223.1/24 up
    ifconfig $(ngctl msg 'host_bridge0:link2' getifname | grep Args | cut -d '"' -f 2) name host_link2

    # Create internal bridge for jails that are forced through wireguard
    ngctl -d -f - <<EOF
mkpeer . eiface hook ether
name .:hook wg_uplink0
EOF

    ngctl -d -f - <<EOF
mkpeer wg_uplink0: bridge ether link0
name wg_uplink0:ether wg_bridge0
EOF

    ngctl -d -f - <<EOF
mkpeer wg_bridge0: eiface link2 ether
name wg_bridge0:link2 wg_link2
EOF

    ifconfig $(ngctl msg 'wg_uplink0:' getifname | grep Args | cut -d '"' -f 2) name wg_uplink0 10.241.199.1/24 up
    ifconfig $(ngctl msg 'wg_bridge0:link2' getifname | grep Args | cut -d '"' -f 2) name wg_link2
}

setup_netgraph_stop() {
    cleanup
}

if [ "$1" = "start" ]; then
    setup_netgraph_start
elif [ "$1" = "stop" ]; then
    setup_netgraph_stop
else
    >&2 echo "Unrecognized command"
fi
