#!/bin/sh

TABLE="4"
TABLENAME=`grep -E "^$TABLE" /etc/iproute2/rt_tables | awk -F' ' '{ print $2 }'`
GW="172.16.69.2"

case "$1" in
up)
	# Clean routes on this table
	ip route flush table "$TABLE" 

	# Add normal rules excluding default one
	ip route show table main | grep -Ev ^default | while read ROUTE ; do ip route add table "$TABLE" $ROUTE; done

	# Add default route pointing to OPENVPN interface
	ip route add table "$TABLE" default via "$GW"

	# Clean up mangle table (assumes we're the only users of this table!)
	while true; do 
	  iptables -t mangle -D OUTPUT 1 2> /dev/null
	  ret=$?
	  if [ $ret -ne 0 ]
	  then 
	    break
	  fi
	done

	# All the traffic coming from squid (user: proxy) should go in the tunnel
	proxy_id=`id -u proxy`
	iptables -t mangle -A OUTPUT -p tcp -m owner --uid-owner $proxy_id -j MARK --set-mark "$TABLE"

	# Route the traffic marked with '4' to the acksyn table
	ip rule add fwmark "$TABLE" table "$TABLE"

	# Flush route cache
	ip route flush cache
	;;
down)
	# Clean routes on this table
	ip route flush table "$TABLE" 

	# Clean up mangle table (assumes we're the only users of this table!)
	while true; do 
	  iptables -t mangle -D OUTPUT 1 2> /dev/null
	  ret=$?
	  if [ $ret -ne 0 ]
	  then 
	    break
	  fi
	done

	# Remove fwmark
	ip rule del fwmark $TABLE table $TABLE 2> /dev/null

	;;
*)
  echo "Usage: $0 {up|down}" >&2
  exit 1
  ;;


esac
exit 0

