#!/usr/local/bin/bash

cleanup() {
    ngctl shutdown nat_link2:
    ngctl shutdown nat_uplink0:
    ngctl shutdown jail_nat_wg0:
}

setup_netgraph_start() {
    cleanup

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

    ngctl -d -f - <<EOF
mkpeer nat_uplink0: bridge ether link0
name nat_uplink0:ether jail_nat_wg0
EOF

    ngctl -d -f - <<EOF
mkpeer jail_nat_wg0: eiface link2 ether
name jail_nat_wg0:link2 nat_link2
EOF

    ifconfig $(ngctl msg 'nat_uplink0:' getifname | grep Args | cut -d '"' -f 2) name nat_uplink0 10.10.11.1/24 up
    ifconfig $(ngctl msg 'jail_nat_wg0:link2' getifname | grep Args | cut -d '"' -f 2) name nat_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