#!/bin/bash
. /etc/kerbynet.conf
#
MASTERCONF="/etc/protonyx.conf"
# Load master.conf
. $MASTERCONF
#
function setDefaultGW {
  G="$1"
  INTERFACE=`cat $G/Interface 2>>$ERROUT`
  IP=`cat $G/IP 2>>$ERROUT`
  DEVICE=`cat $G/Device 2>>$ERROUT`
  # hey instead of ip delete,ip add we can use ip replace which adds or changes if route exists
  # and still delete if the command fails
  #ip ro del default ta 1$G 2>>$ERROUT

  if [ -n "$IP" ] ; then
    # ok this seems to be checking if the specified gateway can actually be used
    # as it fails when it belongs to none of the network interface IP subnets
    # the manager does a much more thourought check on the specified gateway address
    # so we can skip this check to save some time
    #if ip ro add 127.0.0.99 via $IP metric 10 2>>$ERROUT ; then
    #  ip ro del 127.0.0.99 via $IP metric 10
      if [ -n "$DEVICE" ]; then
	DEFROUTE="default via $IP dev $DEVICE"
      else
	DEFROUTE="default via $IP"
      fi
  else
    DEFROUTE="default dev $INTERFACE"
  fi
  if [ $APPLY == "no" ]; then
    RULESET[1$G]="${RULESET[1$G]}\n${DEFROUTE}"
  else
    echo "will now call: ip ro replace $DEFROUTE ta 1$G" >> $ERROUT
    ip ro replace $DEFROUTE ta 1$G 2>>$ERROUT
    if [ $? -ne 0 ]; then
      echo "will now call: ip ro del default ta 1$G" >> $ERROUT
      ip ro del default ta 1$G 2>>$ERROUT
    fi
  fi
    #fi
  #note the double space here. it is important so as to match with the ip ro sh presentation string
  UNREACHROUTE="unreachable default  metric 99"
  if [ $APPLY == "no" ]; then
    RULESET[1$G]="${RULESET[1$G]}\n${UNREACHROUTE}"
  else
    echo "will now call: ip ro add $UNREACHROUTE ta 1$G" >> $ERROUT
    ip ro add $UNREACHROUTE ta 1$G 2>>$ERROUT
  fi
}

. /etc/sysconfig/network-scripts/ifcfg-eth0
if [ "${COMBOXBRIDGE}" = "yes" ]; then
    if [ "${COMBOXBRIDGETEMPLATE}" == "CLIENT" ]; then
	XENOS_IP="${COMBOXBRIDGEXENOSIP}"
	MOREXENOSIPS="${COMBOXBRIDGEMOREXENOSIPS}"
    fi
fi
if [ "$DEBUG" = 0 ]; then
  ERROUT=/dev/null
else
  ERROUT="$DBGFILE"
fi
GW="$1"
OPT="$2"
CONFIG=$REGISTER/system/net/nb
cd $CONFIG/Gateways
if [ -z "$GW" ] ; then 
  GW=`ls -d ?? 2>>$ERROUT`
  ANY=yes
else
  [ -d "$GW" ] || exit 1
  ANY=""
fi
[ -z "$GW" ] && exit 2

APPLY=yes
if [ "$OPT" == flush ] ; then
# AYTO EDW NA FYGEI KAI NA GINEI TO DIFF-STYLE APPLY OTAN MOY ZHTANE FLUSH
#  for G in $GW ; do
#    ip ro flush table 1$G 2>>$ERROUT
#  done
  #ORIGROUTES=`ip ro sh`
  APPLY=no
fi

NEEDNB_SETNEXTHOP=0
#echo 2
while read LINE ; do
  #echo 10
  if echo "$LINE" | egrep -q -v "Unknown|default|nexthop|table|lladdr|FAILED|tos|:|127.0.0." ; then
    if echo "$LINE" | grep -i -w -q ^deleted ; then
      OP=del
      LINE=`echo $LINE | sed -r 's/.eleted//'`
    else
      OP=add
      #an exw flush de xreiazetai na tsekarw an yparxei
      if [ "$OPT" != flush ]; then
        ip ro sh | grep -q "^$LINE" || OP=noop
      fi
    fi
    if [ "$OP" == del ] || [ "$OP" != noop ] && echo $LINE | egrep -q "^[0123456789]{1,3}\.[0123456789]{1,3}\.[0123456789]{1,3}\.[0123456789]{1,3}" ; then
      #if [ -n "$ANY" ] ; then
      #  GW=`ls -d ?? 2>>$ERROUT`
      #fi
      for G in $GW ; do
	if [ "$G" == "00" ]; then
	  continue
	fi
	if [ -n "${XENOS_IP}" ]; then
    	  if [ "$G" != "05" ]; then
	    DONOTCOPY=0;
	    for ANIPADDR in ${XENOS_IP} ${MOREXENOSIPS}; do
	      echo "$LINE"|grep -E -q "${ANIPADDR}[[:blank:]]+dev[[:blank:]]+eth0";RET=$?
              if [ $RET -eq 0 ]; then
                # do not copy this rule please
		DONOTCOPY=1
                break
              fi
	    done
	    if [ $DONOTCOPY -eq 1 ]; then
	      # do not copy this rule please
	      continue
	    fi
	  fi
	fi
	# OBSOLETE - start
#	unset FO_VPN_DOIT
#	if [ "${G}" == "05" ]; then
#	  if [ "${FAILOVER_VPN_ENABLE}" == "yes" ]; then
#	    FO_VPN_DOIT="1"
#	    CONTINUELOOPING="0"
#	    for SUBNET in ${FAILOVER_VPN_REMOTE_SUBNET}; do
#	      echo "$LINE"|grep -E -q "${SUBNET}[[:blank:]]+via[[:blank:]]+.*dev[[:blank:]]+${FAILOVER_VPN_DEVICE}";RET=$?
#              if [ $RET -eq 0 ]; then
#                # do not copy this rule please
#		CONTINUELOOPING="1"
#                break;
#              fi
#	    done
#	    if [ "$CONTINUELOOPING" == "1" ]; then
#	      continue;
#	    fi
#	  fi
#	fi
	# OBSOLETE - end

	if [ $APPLY == "no" ]; then
	  RULESET[1$G]="${RULESET[1$G]}\n${LINE}"
	else
	  echo "will now call: ip ro $OP $LINE ta 1$G" >> $ERROUT
	  ip ro $OP $LINE ta 1$G 2>>$ERROUT
	fi
	if [ "$OPT" != flush ]; then
	  setDefaultGW $G
        fi

	# OBSOLETE - start
#	if [ -n "$FO_VPN_DOIT" ]; then
#	  for SUBNET in ${FAILOVER_VPN_REMOTE_SUBNET}; do
#	    ip ro sh "${SUBNET}" dev tun0 ta 1$G|grep -q .;RET=$?
#	    if [ $RET -ne 0 ]; then
#	      ip ro add "${SUBNET}" dev tun0 ta 1$G
#	    fi
#	  done
#	fi
	# OBSOLETE - end
      done
      
    fi
    # stop doing this for every rule if we are in flush mode. once in the end is enough.
    if [ "$OPT" == flush ]; then
      NEEDNB_SETNEXTHOP=1
    else
      if [ "`cat $REGISTER/system/net/nb/Enabled 2>>$ERROUT`" == yes ] ; then
        $SCRIPTS/nb_setnexthop
      fi
    fi
  fi
done
if [ "$OPT" == flush ]; then
  for G in $GW; do
    if [ "$G" == "00" ]; then
      continue
    fi
    setDefaultGW $G
    # please apply routes now
    ORIGROUTESSORTED=`ip ro sh ta 1$G|sed 's/[[:space:]]*$//g'|sort`
    #NEWROUTESSORTED=`printf "%b" "${RULESET[@]}"|grep -v "^$"|sort`
    NEWROUTESSORTED=`printf "%b" "${RULESET[1$G]}"|sort`
    #printf 'EGW: %b\n' "${RULESET[@]}"
    #printf 'EEEEEEEEEEEIPRO: %s\n' "$ORIGROUTES"
    # compare two vars
    #diff -uN <(printf "%b" "$ORIGROUTESSORTED") <(printf "%b" "$NEWROUTESSORTED")
    NEEDTODELETE=`comm -23 <(echo "$ORIGROUTESSORTED") <(echo "$NEWROUTESSORTED")`
    NEEDTOADD=`comm -13 <(echo "$ORIGROUTESSORTED") <(echo "$NEWROUTESSORTED")`
    # Common routes are already in place
    while read -r ROUTE; do
      if [ -z "$ROUTE" ]; then
	continue;
      fi
      CMD="ip ro del $ROUTE ta 1$G"
      #echo CMD="$CMD"
      echo "will now call: $CMD" >> $ERROUT
      $CMD 2>>$ERROUT
    done <<<"$NEEDTODELETE"
    while read -r ROUTE; do
      if [ -z "$ROUTE" ]; then
        continue;
      fi
      CMD="ip ro add $ROUTE ta 1$G"
      #echo CMD="$CMD"
      echo "will now call: $CMD" >> $ERROUT
      $CMD 2>>$ERROUT
    done <<<"$NEEDTOADD"
  done
fi
if [ $NEEDNB_SETNEXTHOP -eq 1 ]; then
  if [ "`cat $REGISTER/system/net/nb/Enabled 2>>$ERROUT`" == yes ] ; then
    $SCRIPTS/nb_setnexthop
  fi
fi
exit 0
