#!/bin/bash -x

# This script is called with the following arguments:
#    Arg  Name                          Example
#    $1   Interface name                ppp0
#    $2   The tty                       ttyS1
#    $3   The link speed                38400
#    $4   Local IP number               12.34.56.78
#    $5   Peer  IP number               12.34.56.99
#    $6   Optional ``ipparam'' value    foo

# The  environment is cleared before executing this script
# so the path must be reset
PATH=/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin
export PATH

# These variables are for the use of the scripts run by run-parts
[ ! -z "$IFACE" ] && WAN_IFACE=$IFACE || WAN_IFACE="$1"
#WAN_TTY="$2"
#WAN_SPEED="$3"
[ ! -z "$IFACE" ] && WAN_LOCAL=$(ip addr show dev $IFACE  | grep inet | grep -we "eth0$" | awk '{print $2}' | awk -F '/' '{print $1}') || WAN_LOCAL="$4"
WAN_REMOTE="$5"
WAN_GW=$WAN_REMOTE
#WAN_IPPARAM="$6"


# XXX Update it for IPv6


IP=/sbin/ip
IPT=/sbin/iptables
CNT=/usr/sbin/conntrack

VANILLA=eth0


CATCHALL=$VANILLA
CATCHALL_TABLE=catchall

LAN_IF=br0

DEFROUTES=$VANILLA

OVPN_CONFIG_DIR="/etc/openvpn"

CDIR=$(dirname $0)

FIXEDACTIVEDEVS="eth0"
PPPACTIVEDEVS=$(ip link show | grep -B 1 ppp | grep -e "^[0-9]\{1,2\}:" | awk '{print $2}' | rev | cut -b 2- | rev)
#PPPACTIVEDEVS=$(/sbin/ifconfig | grep ppp | awk '{print $0}' | grep -v -w ppp | cut -b -4)
[[ -n $FIXEDACTIVEDEVS && -n $PPPACTIVEDEVS ]] &&  ACTIVEDEVS="$PPPACTIVEDEVS $FIXEDACTIVEDEVS"
[ -z $ACTIVEDEVS ] && [ -n $FIXEDACTIVEDEVS ] && ACTIVEDEVS="$FIXEDACTIVEDEVS"
[ -z $ACTIVEDEVS ] && [ -n $PPPACTIVEDEVS ] && ACTIVEDEVS="$PPPACTIVEDEVS"

MANUAL=/etc/nexdpi
UP=/etc/ppp/ip-up.d
DOWN=/etc/ppp/ip-down.d



echo $ACTIVEDEVS > /tmp/active.devices
echo ${CDIR} > /tmp/mhome.cdir

case ${WAN_IFACE} in
   $VANILLA)
      TABLE="vanilla"
      MARK=1
      ;;
   #$ADEPT)
   #   TABLE="adept"
   #   MARK=2
   #   ;;
   *)
      TABLE="vanilla"
      MARK=1
esac


if [ $MARK != "NO" ] ; then
case ${CDIR} in 
   $UP|$MANUAL)
      [ ${CDIR} = $UP ] && $IP route add default dev $WAN_IFACE table $TABLE || $IP route add default via $WAN_GW table $TABLE
      $IP rule add from $WAN_LOCAL table $TABLE
      $IP rule add fwmark $MARK table $TABLE
      if [ $MARK == 1 ] ; then
         # This is the primary output interface, 
         # so, set also the fwmark used by the shaping system
         for i in $(seq 5 15) ; do
            $IP rule add fwmark $i table $TABLE
         done
      fi

      $IPT -t mangle -I POSTROUTING -o $WAN_IFACE -m mark --mark 0 -j MARK --set-mark $MARK 

      echo 0 > /proc/sys/net/ipv4/conf/$WAN_IFACE/rp_filter # DISABLE MARTIANS FILTERING
      echo 10 > /proc/sys/net/ipv4/route/gc_timeout # FAST ROUTING TABLE CACHE TIMEOUT
      #echo 10 > /prot/sys/net/ipv6/route/gc_timeout  # XXX Do we really need it for ipv6?

      # Dynamic DNS update here!
      # My example works for my own system, but you
      # can add anything here.
      #setsid /usr/bin/wget --timeout=30  -r 10 -t 2 --spider --no-check-certificate --bind-address=$WAN_LOCAL --http-user=mydnsuser --http-password=mydnspwd --quiet https://dns.web.host.com/update/$TABLE 2>&1 > /dev/null

      logger -t "[PPP $WAN_IFACE - $TABLE]" "Connection up (ip $WAN_LOCAL, activedevices $ACTIVEDEVS)"

      for VPN_CONFIG in `cd $OVPN_CONFIG_DIR; ls *.$TABLE.conf 2> /dev/null`; do
        VPN_NAME=${VPN_CONFIG%%.conf}
        cat $OVPN_CONFIG_DIR/$VPN_CONFIG | grep -v "^local" > $OVPN_CONFIG_DIR/$VPN_CONFIG.tmp
        echo "local $WAN_LOCAL" >> $OVPN_CONFIG_DIR/$VPN_CONFIG.tmp
        mv $OVPN_CONFIG_DIR/$VPN_CONFIG.tmp $OVPN_CONFIG_DIR/$VPN_CONFIG
        /etc/init.d/openvpn stop $VPN_NAME >/dev/null 2>&1
        /etc/init.d/openvpn start $VPN_NAME >/dev/null 2>&1
        logger -t "[PPP $TABLE - OpenVPN]" "$VPN_NAME enabled on $WAN_LOCAL" 
      done

       # if this interface is a catchall interface, inject a default route in the special catchall table
       if [ x${WAN_IFACE} = x${CATCHALL} ] ; then
          $IP route del default table catchall
          [ ${CDIR} = $UP ] &&  $IP route add default dev $WAN_IFACE table $CATCHALL_TABLE || $IP route add default via $WAN_GW table $CATCHALL_TABLE
       fi

      ;;
   $DOWN)

      $IPT -t mangle -D POSTROUTING -o $WAN_IFACE -j MARK --set-mark $MARK

      $IP rule del fwmark $MARK table $TABLE
      $IP rule del from $WAN_LOCAL table $TABLE

      # Remove already established connection from the conntrack table
      $CNT -D -m $MARK

      logger -t "[WAN $WAN_IFACE - $TABLE]" "Connection down (ex ip $WAN_LOCAL, activedevices $ACTIVEDEVS)"


     for VPN_CONFIG in `cd $OVPN_CONFIG_DIR; ls *.$TABLE.conf 2> /dev/null`; do
        VPN_NAME=${VPN_CONFIG%%.conf}
        /etc/init.d/openvpn stop $VPN_NAME >/dev/null 2>&1
        logger -t "[WAN $TABLE- OpenVPN]" "$VPN_NAME disabled"
      done

      ;;
esac

$IP route del default 2>&1 > /dev/null
$IP route del default table default 2>&1 > /dev/null

if [ x"$ACTIVEDEVS" != x"" ] ; then 
   DEFR=""
   for iface in $PPPACTIVEDEVS
      do
      DEFR="$DEFR nexthop dev $iface weight 1" 
   done
   for iface in $FIXEDACTIVEDEVS
      do
      DEFR="$DEFR nexthop dev $iface via $WAN_GW weight 1"
   done
   $IP route add default scope global table default $DEFR
   #$IP route  add default equalize $DEFR
fi
$IP route flush cache 
$IP route flush cache table default
fi
