#!/bin/sh -e

### BEGIN INIT INFO
# Provides:          mini-buildd-rep
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start mini-buildd daemon
### END INIT INFO

# Default is to run the daemon
MBD_ENABLE=1
# Source defaults if given
[ ! -e /etc/default/mini-buildd-rep ] || . /etc/default/mini-buildd-rep
if [ "${MBD_ENABLE}" = "0" -a "${1}" != "stop" ]; then
	echo "Starting mini-buildd disabled, skipping (see /etc/default/mini-buildd-rep)."
	exit 0
fi

DAEMON="/usr/bin/mini-dinstall"

if [ "$(id -u -n)" != "root" -a "$(id -u -n)" != "mini-buildd" ]; then
	echo "Either user root or mini-buildd must run this." >&2
	exit 1
fi

if [ ! -x "${DAEMON}" -o ! -e "/home/mini-buildd/.mini-dinstall.conf" ]; then
	exit 0
fi

# Switch between starting as user mini-buildd or root
mbdMiniDinstall()
{
	local pure="${DAEMON} ${1}"
	if [ "$(id -u -n)" = "root" ]; then
		su - mini-buildd -c "${pure}"
	else
		${pure}
	fi
	sleep 1
}

start()
{
	if pgrep -U mini-buildd -f "${DAEMON}" >/dev/null; then
		echo -n "Already started "
	else
		echo -n "Starting "
		mbdMiniDinstall
	fi
	echo -n "$(basename ${DAEMON}) for user mini-buildd: "
	while ! pgrep -U mini-buildd -f "${DAEMON}" >/dev/null; do
		echo -n "."
		sleep 1
	done
	echo "up."
}

stop()
{
	echo -n "Stopping $(basename ${DAEMON}) for user mini-buildd: "

	if pgrep -U mini-buildd -f "${DAEMON}" >/dev/null; then
		mbdMiniDinstall -k >/dev/null || true
	fi

	local count=0
	while pgrep -U mini-buildd -f "${DAEMON}" >/dev/null; do
		echo -n "."
		sleep 1
		count=$((count+1))
		if [ ${count} -gt 20 ]; then
			echo -n "max reached, hard kill"
			pkill -9 -U mini-buildd -f "${DAEMON}"
		fi
	done
	echo "down."
}

reindex()
{
	stop

	local caches=""
	if [ "${1}" = "all" ]; then
		caches="/home/mini-buildd/rep/*.db"
	else
		caches="/home/mini-buildd/rep/${1}.db"
	fi
	rm -v ${caches} || true

	start
}

usage()
{
	echo "Usage: $0 {start|stop|restart|force-reload|reindex all|DIST}" >&2
	exit 1
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart|force-reload)
		stop
		start
		;;
	reindex)
		[ -n "${2}" ] || usage
		reindex "${2}"
		;;
	*)
		usage
		;;
esac

exit 0
