#!/bin/bash
set -e

if [ "$EUID" -ne 0 ]; then
  echo "Error: please run as root!"
  exit 1
fi

if [[ ! ( -f "$SNAP_USER_DATA/internal.firewall-control-connected" && -f "$SNAP_USER_DATA/internal.network-control-connected" ) ]]; then
    echo "Error: please connect interfaces"
    sleep infinity
fi

for var in "$@"
do
    if [[ "$found" == true ]]; then
        CONFIG_FILE="$var"
        # echo "true $CONFIG_FILE"
        break
    fi
    if [[ "$var" == "--config" ]]; then
        found=true
    fi
done

if [[ ! -f "$CONFIG_FILE" ]]; then
    echo "Error: please generate config"
    sleep infinity
fi    

regex="^server\s+(.*)\s+(.*)"
while IFS= read -r line
do
    # echo $line
    if [[ "$line" =~ $regex ]]
    then
        TUNNEL_ADDRESS="${BASH_REMATCH[1]}"
        TUNNEL_NETMASK="${BASH_REMATCH[2]}"
        echo "ip ${TUNNEL_ADDRESS}"
        echo "nm ${TUNNEL_NETMASK}"
    fi
done < "$CONFIG_FILE"

iptables -t nat -A POSTROUTING -s $TUNNEL_ADDRESS/$TUNNEL_NETMASK -j MASQUERADE -m comment --comment "generated by easy-openvpn-server"

regex="^server-ipv6\s+(.*)\s*"
while IFS= read -r line
do
    # echo $line
    if [[ "$line" =~ $regex ]]
    then
        TUNNEL_NETWORK_6="${BASH_REMATCH[1]}"
        echo "ipv6 network: ${TUNNEL_NETWORK_6}"
    fi
done < "$CONFIG_FILE"

# Note: see ipv6.md for more info on why we're using MASQUERADE NAT.
ip6tables -t nat -A POSTROUTING -s $TUNNEL_NETWORK_6 -j MASQUERADE -m comment --comment "generated by easy-openvpn-server"

ORIG_FORWARD_VALUE=$(sysctl net.ipv4.ip_forward -b)
sysctl -w net.ipv4.ip_forward=1
sysctl -w net.ipv6.conf.all.forwarding=1
# https://strugglers.net/~andy/blog/2011/09/04/linux-ipv6-router-advertisements-and-forwarding/
sysctl -w net.ipv6.conf.all.accept_ra=2

function cleanup {
  echo Cleaning up...
  #sysctl -w net.ipv4.ip_forward=${ORIG_FORWARD_VALUE}
  iptables -t nat -D POSTROUTING -s $TUNNEL_ADDRESS/$TUNNEL_NETMASK -j MASQUERADE -m comment --comment "generated by easy-openvpn-server"
  ip6tables -t nat -D POSTROUTING -s $TUNNEL_NETWORK_6 -j MASQUERADE -m comment --comment "generated by easy-openvpn-server"
}
trap cleanup EXIT

# Execute normally instead of with exec so our trap works correctly.
$@
