#!/bin/sh
# description: UTM Billing System DHCP Safe start script

pid_file=/var/run/utm5_dhcpd.pid
safe_pid_file=/var/run/safe_utm5_dhcpd.pid
utm_exec=utm5_dhcpd
err_log=/netup/utm5/log/dhcp.log
exec_dir=/netup/utm5/bin
dhcp_flags=""
dhcp_cfg=/netup/utm5/dhcpd5.cfg


#  Check if allready started
if [ -r ${safe_pid_file} ] && kill -0 "`head -n1 ${safe_pid_file}`" 2>/dev/null
then
    echo "`basename ${0}` allready started"
    exit 1
fi

#  Save PID into pidfile
echo $$ > ${safe_pid_file}


#  Check if daemon allready executed
if [ -r ${pid_file} ] && kill -0 "`head -n1 ${pid_file}`" 2>/dev/null
then
    PID=`head -n1 ${pid_file}`
    echo "${utm_exec} allready started with PID ${PID}"
else
    PID=
fi

#  Close all file descriptors
case `uname` in
    Linux)
        FD_PATH=/proc/self/fd
        ;;
    FreeBSD)
        FD_PATH=/dev/fd
        ;;
    *)
        echo "Unrecognized operation system, skip closing file descriptors"
        FD_PATH=
        ;;
esac
if [ "${FD_PATH}" ]; then
    for FD in `ls ${FD_PATH}`; do
        eval "exec ${FD}<&-"
    done
fi

while true; do
    if ! kill -0 "${PID}" 2>/dev/null; then
        $exec_dir/$utm_exec $dhcp_flags -c $dhcp_cfg >>$err_log 2>&1 &
        PID=$!
        sleep 5
    fi
    wait
done
