#!/bin/sh
#
# Script to remove the IPTABLE rule which open TCP port 4118
# In general, /etc/init.d/ds_agent service script fork call to this script on ds_agent service stop
#
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

MAX_WAIT_TIME=60
CHECK_INTERVAL=2

# do nothing if user does not allow or iptable is inactive
if [ -f /etc/use_dsa_with_iptables ]; then
   logger -t dsa_port_remove "Do not touch firewall"
   exit
fi

# singleton protection
if [ -e ${RM_LOCKFILE} ] && kill -0 `cat ${RM_LOCKFILE}`; then
   logger -t dsa_port_remove "$RM_PROG already running"
   exit
fi

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

Firewall_Enabled=$(checkFirewallEnabled);
if [ $Firewall_Enabled -eq 0 ]; then
   logger -t dsa_port_remove "Firewall is not enabled"
   exit
fi


# if dsa_port_add is running, wait for it to exit
for (( i=0; i<$MAX_WAIT_TIME; ++i )); do

    if [ -e ${ADD_LOCKFILE} ] && kill -0 `cat ${ADD_LOCKFILE}`; then
       sleep $CHECK_INTERVAL 
       logger -t dsa_port_remove "wait for $ADD_PROG to exit"
       continue
    else
       break
    fi

done

# remove port 4118 open rule from iptables anyway
if ! tcp_port_4118_filtered; then
   for command in iptables ip6tables; do
      $command -D ${IPTABLE_OPEN_4118_RULE} 2>/dev/null
   done
   logger -t dsa_port_remove "remove TCP port 4118 open rule from IPTABLES"
fi

# clean up lockfile on exit
rm -f ${RM_LOCKFILE}
