#!/bin/sh
#
# Script to insert the IPTABLE rule to open TCP port 4118
# In general, /etc/init.d/ds_agent service script fork call to this script on service start
#

exec_bin="/opt/ds_agent"
. $exec_bin/dsa_common

ADD_PROG=`basename $exec_bin/dsa_port_add`
ADD_LOCKFILE=/var/lock/subsys/$ADD_PROG

RM_PROG=`basename $exec_bin/dsa_port_remove`
RM_LOCKFILE=/var/lock/subsys/$RM_PROG

declare -r MAX_WAIT_TIME=10
declare -r CHECK_INTERVAL=2

is_dsa_port_remove_running()
{
   if [ -e ${RM_LOCKFILE} ]; then
      echo 1
   else
      echo 0
   fi
}

# do nothing if user does not allow to modify IPTABLES or FireWall is not enabled
if [ -f /etc/use_dsa_with_iptables ]; then
   logger -t dsa_port_add "Do not touch firewall"
   exit
fi

# singleton protection
if [ -e ${ADD_LOCKFILE} ]; then
   logger -t dsa_port_add "$ADD_PROG already running"
   exit
fi

# make sure cleanup indeed happen on leave
trap "rm -f ${ADD_LOCKFILE}; exit" INT TERM EXIT
echo $$ > ${ADD_LOCKFILE}

isSuSE=0
if [ -f /etc/SuSE-release ]; then
   isSuSE=1
fi

Firewall_Enabled=$(checkFirewallEnabled);
if [ $Firewall_Enabled -eq 0 -a $isSuSE -eq 0 ]; then
   logger -t dsa_port_add "Firewall is not enabled, stop inserting port 4118 open rule."
   exit
fi

# On certain Linux platforms like SuSE, firewall status is not stable during booting. 
# IPTABLEs rules are set after agent start especially on system boot.
# To make sure port 4118 is open successfully, we do rule try/insert for certain period of time
LOOP_COUNT=1 
if [ $isSuSE -eq 1 ]; then
  LOOP_COUNT=$MAX_WAIT_TIME
fi

for (( i=0; i<$LOOP_COUNT; ++i )); do
   
   if [ $isSuSE -eq 1 ]; then
      Firewall_Enabled=$(checkFirewallEnabled)
      if [ $Firewall_Enabled -eq 0 ]; then
         sleep $CHECK_INTERVAL
         continue
      fi
   fi

   # Bail out if dsa_port_remove script is up running. ds_agent service is shutting down.
   rm_running=$(is_dsa_port_remove_running)
   if [ $rm_running -eq 1 ]; then
      logger -t dsa_port_remove "bail out dsa_port_add as dsa_port_remove was kicked off"
      break
   fi  

   # insert rule if TCP port 4118 is not open yet   
   if tcp_port_4118_filtered; then
       
       for command in iptables ip6tables; do
          $command -I ${IPTABLE_OPEN_4118_RULE} 2>/dev/null
       done

       logger -t dsa_port_add "dsa_port_add insert iptables rule to open TCP port 4118"
   else 
       logger -t dsa_port_add "TCP port 4118 is already open"
   fi

   sleep $CHECK_INTERVAL
   
   if [ $isSuSE -eq 1 ]; then
      logger -t dsa_port_add "dsa_port_add keep wait checking..."
   fi

done

logger -t dsa_port_add "dsa_port_add exit"

# clean up LOCKFILE on exit
rm -f ${ADD_LOCKFILE}
