#!/bin/sh
#
# Start ipforwarding.
# Set iptables rules.
#

source /opt/gira/share/devicestack/ipmodule-vars

me=[S16firewall]

start() {
  # Change Forward chain policy to DROP as we only want to forward what we nee to.
  iptables --policy FORWARD DROP
  if [ -f ${OPENVPN_ENABLED_FILE} ]
  then
    echo -n "${me} Enable ip forwarding and set iptables: "
    # To avoid further changes to the GDS extract VPN server network
    # and local network from VPN fragments created by the GDS.
    LOCAL_SUBNET=$(cat ${OPENVPN_CONFIG_DIR}/vpnserver2.fragment | grep route | cut -d ' ' -f 3)
    VPN_SUBNET=$(cat ${OPENVPN_CONFIG_DIR}/vpnserver2.fragment | grep server | cut -d ' ' -f 2)
    iptables -A FORWARD -i tun0 -o br0 -s ${VPN_SUBNET}/24 -d ${LOCAL_SUBNET}/24 -j ACCEPT
    iptables -A FORWARD -i br0 -o tun0 -d ${VPN_SUBNET}/24 -s ${LOCAL_SUBNET}/24 -j ACCEPT
    iptables -t nat -A POSTROUTING -o br0 -s ${VPN_SUBNET}/24 -j MASQUERADE
    sysctl -w net.ipv4.ip_forward=1
    echo "OK"
  fi
}

stop() {
  echo -n "${me} Stopp ip forwarding: "
  sysctl -w net.ipv4.ip_forward=0
  echo "OK"
}

case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart|reload)
	stop
	start
	;;
  *)
	echo "${me} Usage: $0 {start|stop|restart}"
	exit 1
esac

exit $?
