#! /bin/sh
# version 0.5
IPTABLES=/usr/sbin/iptables

mkdir -p /var/run

# Check if the custom chains already exist.
if ! $IPTABLES -L DOMOTZVPN_INPUT -n >/dev/null 2>&1; then
    $IPTABLES -N DOMOTZVPN_INPUT
fi

if ! $IPTABLES -L DOMOTZVPN_FORWARD -n >/dev/null 2>&1; then
    $IPTABLES -N DOMOTZVPN_FORWARD
fi

# Remove the previous rules from the new custom chains
$IPTABLES -D DOMOTZVPN_INPUT -p tcp --dport 31194 -j ACCEPT
$IPTABLES -D DOMOTZVPN_FORWARD -s 10.177.0.0/24 -j ACCEPT
$IPTABLES -D DOMOTZVPN_FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

# Add rules for the custom chains DOMOTZVPN_INPUT and DOMOTZVPN_FORWARD
# the first rule accept all traffic to port 31194 from WAN to anable access to the VPN server
$IPTABLES -A DOMOTZVPN_INPUT -p tcp --dport 31194 -j ACCEPT
# the second rule accept all traffic from the VPN subnet To enable the VPN Client to site
$IPTABLES -A DOMOTZVPN_FORWARD -s 10.177.0.0/24 -j ACCEPT
# the third rule accept all traffic that is related or established
$IPTABLES -A DOMOTZVPN_FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

# Add the custom chains to the INPUT and FORWARD chains.
$IPTABLES -I INPUT -j DOMOTZVPN_INPUT
$IPTABLES -I FORWARD -j DOMOTZVPN_FORWARD

# Clean all the SNAT POSTROUTING rules added
remove_snat () {
NOWRULES="$($IPTABLES --line-number -nL -t nat | grep '10.177.0.0' | awk '{print $1}' | tac)"
for rul in $NOWRULES
do
        $IPTABLES -t nat -D POSTROUTING $rul
        sleep 0.1
done
}

# Count the number of interfaces connected to default gateway
COUNT_DEVICE_DEFAULT="$(ip addr show | awk '/inet.*brd/{print $NF}' | grep -v tun0 | wc -l)"

if [ $COUNT_DEVICE_DEFAULT -gt 1 ]; then
# if there are more than 1 interface connected to default gateway then remove the MASQUERADE rule and add it again
# to enable the VPN traffic to reach the WAN
        $IPTABLES -t nat -D POSTROUTING -j MASQUERADE
        $IPTABLES -t nat -A POSTROUTING -j MASQUERADE
else
# if there is only 1 interface connected to default gateway then remove the SNAT rule and add it again
# to enable the VPN traffic to reach the WAN
        IP="$(ip addr show "$(awk '$2 == 00000000 { print $1 }' /proc/net/route | uniq)" | grep -v inet6 | awk '$1 ~ /^inet/ { sub("/.*", "", $2); print $2 }')"
        export IP
        remove_snat
        $IPTABLES -t nat -A POSTROUTING -s 10.177.0.0/24 ! -d 10.177.0.0/24 -j SNAT --to $IP
fi