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

pid_file=/var/run/utm5_traffic_collector.pid
utm_exec=utm5_traffic_collector
err_log=/netup/utm5/log/traffic_collector.log
exec_dir=/netup/utm5/bin
root_email=root
tc_flags=""
tc_cfg=/netup/utm5/utm5_traffic_collector.cfg

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

case "$1" in
start)
        if [ -x $exec_dir/$utm_exec ]; then
            echo "Starting utm5_traffic_collector"
			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_traffic_collector process already exists"
					echo "A utm5_traffic_collector 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_traffic_collector not started"
					exit 1
				fi
			fi
			while true
			do
    		  $exec_dir/$utm_exec $tc_flags -c $tc_cfg >>$err_log 2>&1 
			  if test ! -f $pid_file
			  then
				break
			  fi
				echo "utm5_traffic_collector process exited ... Check it" | mail $root_email
				echo "utm5_traffic_collector process exited ... mail to admin sent. Sleeping 10 sec!"
				sleep 10
		    done
        fi
        ;;
stop)
        echo "Stopping utm5_traffic_collector"
        if [ -r $pid_file ]
        then
          tc_pid=`cat $pid_file`
		  rm -f $pid_file
          kill -9 $tc_pid >>$err_log 2>&1
        else  
		  rm -f $pid_file >>$err_log 2>&1
          killall -9 $utm_exec >>$err_log 2>&1
        fi
        ;;
*)
        echo "Usage: `basename $0` {start|stop}" >&2
        exit 64
        ;;
esac
