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

pid_file=/var/run/utm5_core.pid
cfg_file=/netup/utm5/utm5.cfg
utm_exec=utm5_core
err_log=/netup/utm5/log/utm5_core.log
exec_dir=/netup/utm5/bin
root_email=root

if [ -r $cfg_file ]
then
  . $cfg_file
fi



case "$1" in
start)
        if [ -x $exec_dir/$utm_exec ]; then
            echo "Starting utm5_core"
			if test -f $pid_file
			then
				PID=`cat $pid_file`
				if /bin/kill -0 $PID > /dev/null 2> /dev/null
				then
					if /bin/ps p $PID | grep $utm_exec > /dev/null
					then    # The pid contains a utm5_core process
					echo "A utm5_core process already exists"
					echo "A utm5_core 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_core not started"
					exit 1
				fi
			fi
			while true
			do
			rm -f $pid_file      
			$exec_dir/$utm_exec
			if test ! -f $pid_file
			then
				break
			fi
				echo "utm5_core process exited ... Check it" | mail $root_email
				echo "utm5_core process exited ... mail to admin sent. Sleeping 5 sec!"
				sleep 30
			done
        fi
        ;;
stop)
        echo "Stopping utm5_core"
        if [ -r $pid_file ]
        then
          core_pid=`cat $pid_file`
          rm -f $pid_file >/dev/null 2>/dev/null
          kill -SIGUSR1 $core_pid >>$err_log 2>&1
        else
          rm -f $pid_file >/dev/null 2>/dev/null
          killall -SIGUSR1 utm5_core >>$err_log 2>&1
        fi  
        exit 0
        
        ;;
*)
        echo "Usage: `basename $0` {start|stop}" >&2
        exit 64
        ;;
esac
