#!/bin/sh
#
# $Id
#

# PROVIDE: logdispatcher
# REQUIRE: mountsafe DAEMON
# KEYWORD: shutdown

# Define logdispatcher_* variables in /etc/rc.conf.d/logdispatcher
# Add the following line to this file to enable logdispatcher:
# logdispatcher_enable="YES"
#

. /etc/rc.subr

name="logdispatcher"
rcvar=${name}_enable

load_rc_config $name

: ${logdispatcher_enable="NO"}
: ${logdispatcher_user="webbase"}
: ${logdispatcher_dir="/Berkanavt/spider"}
: ${logdispatcher_flags="-h ${logdispatcher_dir} DispatchLogel -c"}
: ${logdispatcher_start_log="${logdispatcher_dir}/logs/${name}.start"}

command="${logdispatcher_dir}/bin/fut"
command_args="${logdispatcher_flags}"

pidfile="${logdispatcher_dir}/run/${name}.pid"
checkfile="${logdispatcher_dir}/run/${name}.stoped"

required_dirs="${logdispatcher_dir}/outlogs ${logdispatcher_dir}/copylogs"

extra_commands="checkup"
start_precmd="${name}_prestart"
start_cmd="${name}_start"
stop_postcmd="${name}_poststop"
checkup_cmd="${name}_checkup"

is_spider ()
{
    if [ -z `/Berkanavt/bin/scripts/spiderlookup -w` ] ; then
        return 1
    fi
}

check_running ()
{
    is_spider || exit
    if [ -n "$rc_pid" -a -z "$rc_fast" ] ; then
        return 0
    else
        return 1
    fi
    return 1
}

logdispatcher_prestart ()
{
    if check_running ; then
        echo "already running"
        return 1
    else
        if [ -n "$logdispatcher_user" ]; then
            if [ "$logdispatcher_user" = "$(eval $IDCMD)" ]; then
                # unset $logdispatcher_user if running as that user
                unset logdispatcher_user
            fi
        fi

        if ! find ${logdispatcher_dir}/outlogs \( -type f -or -type s \) -delete; then
            return 1
        fi
        if [ -f $checkfile ]; then
            rm -f $checkfile
        fi
        if [ "$(eval $IDCMD)" = "root" ]; then
            if ! newsyslog -sR "${name} rc script" ${logdispatcher_start_log}; then
                return 1
            fi
        fi
    fi
    return 0
}

logdispatcher_start ()
{
    if ! daemon -p $pidfile ${logdispatcher_user:+-u$logdispatcher_user} $command \
        $command_args >>${logdispatcher_start_log} 2>&1
    then
        echo "start ${name} failed"
        return 1
    else
        echo "${name} is started."
        return 0
    fi
}

logdispatcher_poststop ()
{
    if ! touch $checkfile; then
        echo "failed create ${checkfile}"
        return 1
    else
        return 0
    fi
}

logdispatcher_checkup ()
{
    if ! check_running ; then
        if [ -f "$checkfile" ]; then
            return 0
        else
            _run_rc_notrunning
            logdispatcher_start
        fi
    fi
}

run_rc_command "$1"

