#!/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
    printf "%s Enable ip forwarding and set iptables: " "${me}"
    # 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
    printf "OK\\n"
  fi
}

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

case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart|reload)
	stop
	start
	;;
  *)
	printf "%s Usage: %s {start|stop|restart}\\n" "${me}" "$0"
	exit 1
esac

exit $?
