#!@l_prefix@/bin/openpkg rc
##
##  rc.dhcpd -- Run-Commands
##

%config
    dhcpd_enable="$openpkg_rc_def"
    dhcpd_flags="-q"
    dhcpd_if=""
    dhcpd_port="67"
    dhcpd_log_prolog="true"
    dhcpd_log_epilog="true"
    dhcpd_log_numfiles="10"
    dhcpd_log_minsize="1M"
    dhcpd_log_complevel="9"

%common
    dhcpd_pidfile="@l_prefix@/var/dhcpd/run/dhcpd.pid"
    dhcpd_leases="@l_prefix@/var/dhcpd/db/dhcpd.leases"
    dhcpd_signal () {
        if [ ! -f $dhcpd_pidfile ]; then return 1; fi
        kill -$1 `cat $dhcpd_pidfile`
    }
    dhcpd_start () {
        if [ ! -f $dhcpd_leases ]; then
            touch $dhcpd_leases
            chmod 644 $dhcpd_leases
            chown @l_susr@:@l_mgrp@ $dhcpd_leases
        fi
        local cmd="@l_prefix@/sbin/dhcpd"
        cmd="$cmd -f"
        cmd="$cmd $dhcpd_flags"
        echo ".$dhcpd_flags" | grep -- -p >/dev/null 2>&1
        if [ $? -ne 0 -a ".$dhcpd_port" != . ]; then
            cmd="$cmd -p $dhcpd_port"
        fi
        if [ $# -gt 0 ]; then
            cmd="$cmd $@"
        fi
        ( eval "nohup $cmd </dev/null >/dev/null 2>&1 &"
          echo $! >$dhcpd_pidfile
        ) >/dev/null 2>&1
    }

%status -u @l_susr@ -o
    dhcpd_usable="unknown"
    dhcpd_active="no"
    @l_prefix@/sbin/dhcpd -q -t || dhcpd_usable="no"
    [ ".$dhcpd_if" = . ] && dhcpd_usable="no"
    rcService dhcpd enable yes && \
        dhcpd_signal 0 && dhcpd_active="yes"
    echo "dhcpd_enable=\"$dhcpd_enable\""
    echo "dhcpd_usable=\"$dhcpd_usable\""
    echo "dhcpd_active=\"$dhcpd_active\""

%start -u @l_susr@
    rcService dhcpd enable yes || exit 0
    rcService dhcpd usable no  && exit 0
    rcService dhcpd active yes && exit 0
    dhcpd_start $dhcpd_if

%stop -u @l_susr@
    rcService dhcpd enable yes || exit 0
    rcService dhcpd active no  && exit 0
    dhcpd_signal TERM
    sleep 2
    rm -f $dhcpd_pidfile 2>/dev/null || true

%restart -u @l_susr@
    rcService dhcpd enable yes || exit 0
    rcService dhcpd active no  && exit 0
    rc dhcpd stop start

%reload -u @l_susr@
    rcService dhcpd enable yes || exit 0
    dhcpd_signal HUP

%daily -u @l_susr@
    rcService dhcpd enable yes || exit 0
    rcTmp -i
    hintfile=`rcTmp -f -n hint`
    for tool in dhcpd dhclient dhrelay omshell; do
        shtool rotate -f \
            -n $dhcpd_log_numfiles -s $dhcpd_log_minsize -d \
            -z $dhcpd_log_complevel -m 644 -o @l_susr@ -g @l_mgrp@ \
            -P "$dhcpd_log_prolog" \
            -E "$dhcpd_log_epilog; echo 1 >$hintfile" \
            @l_prefix@/var/dhcpd/log/$tool.log
    done
    if [ -s $hintfile ]; then
        rc dhcpd restart
    fi
    rcTmp -k

