#!/bin/sh
#
# $Id
#

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

# Define spider_* variables in /etc/rc.conf.d/spider
# Add the following line to this file to enable spider:
# spider_enable="YES" 
# 

. /etc/rc.subr

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

load_rc_config $name

: ${spider_enable="NO"}
: ${spider_user="webbase"}
: ${spider_dir="/Berkanavt/spider"}
: ${spider_name="spider"}
: ${spider_lookup="/Berkanavt/bin/scripts/spiderlookup"}
: ${spider_flags="-C /Berkanavt/config/config.spider"}
: ${spider_start_log="${spider_dir}/logs/${name}.start"}

command="${spider_dir}/bin/${spider_name}"
command_args="${spider_flags}"

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

required_files="${spider_lookup}"
required_dirs="${spider_dir}/temp ${spider_dir}/queue"

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
}

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

		if ! find ${spider_dir}/temp \( -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" ${spider_start_log}; then
				return 1
			fi
		fi
	fi
	return 0
}

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

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

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

run_rc_command "$1"

