#!/bin/sh
# chkconfig: 2345 90 10
# description: UTM Billing System DHCP server control tool

### BEGIN INIT INFO
# Provides: utm5_dhcp
# Required-Start: $utm5_core $syslog
# Required-Stop: $utm5_core $syslog
# Should-Start: $network $time
# Should-Stop: $network $time
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: utm5_dhcp
# Description: UTM Billing System DHCP server control tool
### END INIT INFO

utm_exec=safe_utm5_dhcp
err_log=/netup/utm5/log/dhcp.log
exec_dir=/netup/utm5/bin
pid_file=/var/run/utm5_dhcpd.pid
safe_pid_file=/var/run/safe_utm5_dhcpd.pid


case "$1" in
start)
    if [ -r ${safe_pid_file} ] && \
       kill -0 "`head -n1 ${safe_pid_file}`" 2>/dev/null
    then
        echo "Service ${utm_exec} allredy started"
        exit 0
    fi
    if ! [ -x $exec_dir/$utm_exec ]; then
        echo "Service ${utm_exec} not found"
        exit 1
    fi

    $exec_dir/$utm_exec &
    ;;
stop)
    if [ -r ${safe_pid_file} ]; then
        PID=`head -n1 ${safe_pid_file}`
        if kill -0 "${PID}" 2>/dev/null; then
            echo "Helper found, stopping"
            kill -9 "${PID}"
        fi
    fi
    
    if [ -r ${pid_file} ]; then
        PID=`head -n1 ${pid_file}`
        if kill -0 "${PID}" 2>/dev/null; then
            echo "Service found, stopping"
            kill "${PID}"
            sleep 1
            T=30
            while kill -0 "${PID}" 2>/dev/null; do
                if [ ${T} -le 0 ]; then
                    echo "Can't terminate service, killing!" >&2
                    kill -9 "${PID}"
                    exit 1
                fi
                sleep 1
                T=$(( ${T} - 1 ))
            done
        fi
    fi
    ;;
*)
        echo "Usage: `basename $0` {start|stop}" >&2
        exit 64
        ;;
esac

