#!/bin/sh
#
# $Id$
#

# PROVIDE: mirrors
# REQUIRE: DAEMON
# KEYWORD: shutdown

. /etc/rc.subr

name="mirrors"
rcvar=`set_rcvar`

load_rc_config $name

# Defaults
: ${mirrors_enable="NO"}
: ${mirrors_root="/Berkanavt/${name}"}
: ${mirrors_user="${name}"}
: ${mirrors_bindir="${mirrors_root}/bin"}
: ${mirrors_configdir="${mirrors_root}/config"}
: ${mirrors_queuedir="${mirrors_root}/queue"}
: ${mirrors_rundir="${mirrors_root}/run"}
: ${mirrors_logdir="${mirrors_root}/logs"}
: ${mirrors_tmpdir="${mirrors_root}/temp"}
: ${mirrors_checkfile="${mirrors_rundir}/disable_check"}
: ${mirrors_args="${mirrors_queuedir}/${name}.tsk.ip -h ${mirrors_root} -C ${mirrors_configdir}/mirror-spider.cfg"}
: ${mirrors_start_log="${mirrors_logdir}/${name}.start"}

command="${mirrors_bindir}/mirror-spider"
command_args="${mirrors_args}"

pidfile="${mirrors_rundir}/${name}.pid"

# Custom commands
extra_commands="check"
start_precmd="${name}_prestart"
start_cmd="${name}_start"
start_postcmd="${name}_poststart"
stop_postcmd="${name}_poststop"
check_cmd="${name}_check"

mirrors_prestart()
{
	if [ -z "$rc_fast" -a -n "$rc_pid" ]; then
		echo 1>&2 "${name} already running? (pid=$rc_pid)."
		return 1
	fi

	if ! find $mirrors_tmpdir -depth 1 \( -type f -or -type s \) -delete; then
		return 1
	fi

	if [ -f $mirrors_checkfile ]; then
		rm -f $mirrors_checkfile
	fi

	if [ "$(eval $IDCMD)" = "root" ]; then
		if ! newsyslog -sR "${name} rc script" ${mirrors_start_log}; then
			return 1
		fi
	fi

	return 0
}

mirrors_start()
{
	echo "Starting ${name}."

	if [ -n "$mirrors_user" ]; then
		if [ "$mirrors_user" = "$(eval $IDCMD)" ]; then
			# unset $mirrors_user if running as that user
			unset mirrors_user
		fi
	fi           

	if ! daemon -p $pidfile ${mirrors_user:+-u$mirrors_user} $command \
		$rc_flags $command_args >/dev/null 2>${mirrors_start_log}
	then
		return 1
	fi

	return 0
}

mirrors_poststart()
{
	if [ -n "${mirrors_user}" ]; then
		# Mirrors scripts need to get spider's PID from pidfile but
		# daemon(8) creates pidfile with owner `who runs daemon(8)' and
		# permissions 600. So we need to fix pidfile permissions.
		if ! chmod +r ${pidfile}; then
			return 1
		fi
	fi
}

mirrors_poststop()
{
	if ! touch $mirrors_checkfile; then
		return 1
	fi

	if [ -f "${pidfile}" ]; then
		rm -f $pidfile || true
	fi

	return 0
}

mirrors_check()
{
	if [ -n "$rc_pid" ]; then
		return 0
	else
		if [ -f "$mirrors_checkfile" ]; then
			return 0
		else
			echo "${name} is not running."
			return 1
		fi
	fi
}

run_rc_command "$1"
