#!/bin/sh
# description: UTM Billing System Radius Safe start script
trap '' 1 2 3 15

pid_file=/var/run/utm5_rfw.pid
utm_exec=utm5_rfw
err_log=/netup/utm5/log/rfw5.log
exec_dir=/netup/utm5/bin
root_email=root
rfw_flags=""
rfw_cfg=/netup/utm5/rfw5.cfg

if [ -r $rfw_cfg ]; then
  . $rfw_cfg
fi

case "$1" in
start)
        if [ -x $exec_dir/$utm_exec ]; then
            echo "Starting utm5_rfw"
			if test -f $pid_file
			then
				PID=`cat $pid_file`
				if /bin/kill -9 $PID > /dev/null 2> /dev/null
				then
					if /bin/ps p $PID | grep $utm_exec > /dev/null
					then    # The pid contains a utm5_radius process
					echo "A utm5_rfw process already exists"
					echo "A utm5_rfw process already exists at " `date` >> $err_log
					exit 1
					fi
				fi
				rm -f $pid_file
				if test -f $pid_file
				then
					echo "Fatal error: Can't remove the pid file: $pid_file"
					echo "Fatal error: Can't remove the pid file: $pid_file at " `date` >> $err_log
					echo "Please remove it manually and start $0 again"
					echo "utm5_rfw not started"
					exit 1
				fi
			fi
			while true
			do
    		  $exec_dir/$utm_exec $rfw_flags -c $rfw_cfg >>$err_log 2>&1 
			  if test ! -f $pid_file
			  then
				break
			  fi
				echo "utm5_rfw process exited ... Check it" | mail $root_email
				echo "utm5_rfw process exited ... mail to admin sent. Sleeping 10 sec!"
				sleep 10
		    done
        fi
        ;;
stop)
        echo "Stopping utm5_rfw"
        if [ -r $pid_file ]
        then
          rfw_pid=`cat $pid_file`
		  rm -f $pid_file
          kill -SIGKILL $rfw_pid >>$err_log 2>&1
        else  
		  rm -f $pid_file >>$err_log 2>&1
          killall -SIGKILL $utm_exec >>$err_log 2>&1
        fi
        ;;
*)
        echo "Usage: `basename $0` {start|stop}" >&2
        exit 64
        ;;
esac
