#!/bin/sh

cd /usr/local/cutedge/openvpn/scripts

if ( test `sysctl -n net.inet.ip.forwarding` == 0 ) then
    sysctl -w net.inet.ip.forwarding=1
    #sysctl -w net.inet.ip.fw.enable=1
fi

printf '%s\n' "$(cat /etc/pf.conf | sed '/^###Start OpenVPNEnabler###/,/^###End OpenVPNEnabler###/d ; /^###Start Cutedge###/,/^###End Cutedge###/d')" | sed '/./,$!d' | awk '
{ print }
/^nat-anchor/ {
    print "###Start OpenVPNEnabler###"
    print "nat-anchor \"com.cutedgesystems.openvpn\""
    print "load anchor \"com.cutedgesystems.openvpn\" from \"/usr/local/cutedge/openvpn/scripts/pfrules\""
    print "###End OpenVPNEnabler###"
}
' | awk '
{ print }
END {
    print ""
    print "###Start Cutedge###"
    print "anchor \"com.cutedgesystems.fw\""
    print "load anchor \"com.cutedgesystems.fw\" from \"/usr/local/cutedge/openvpn/scripts/fwrules\""
    print "###End Cutedge###"
}
' > pf.tmp
mv pf.tmp /etc/pf.conf

pfctl -d
sleep 1
pfctl -F all
sleep 1
pfctl -f /etc/pf.conf -e
