#! /bin/sh
# Copyright (c) 2007, Novell Inc.
#
# Author: adrian@suse.de

. /etc/sysconfig/obs-server

# Determine the base and follow a runlevel link name.
base=${0##*/}
link=${base#*[SK][0-9][0-9]}

if [ -z "$OBS_RUN_DIR" ]; then
        OBS_RUN_DIR="/srv/obs/run"
fi

if [ -z "$OBS_LOG_DIR" ]; then
        OBS_LOG_DIR="/srv/obs/log"
fi

if [ -n "$OBS_BACKENDCODE_DIR" ]; then
	obsdir="$OBS_BACKENDCODE_DIR"
else
	obsdir=/usr/lib/obs/server
fi
rundir="$OBS_RUN_DIR"
logdir="$OBS_LOG_DIR"

OBS_NEW_SCHEDULER_ARCHITECTURES=`$obsdir/bs_admin --show-scheduler-architectures 2>/dev/null`

if test -n "$OBS_NEW_SCHEDULER_ARCHITECTURES" ; then
	if test -n "$OBS_SCHEDULER_ARCHITECTURES" ; then
		echo "WARNING: ignoring old scheduler architectures configuration from /etc/sysconfig/obs-server"
	fi
	OBS_SCHEDULER_ARCHITECTURES="$OBS_NEW_SCHEDULER_ARCHITECTURES"
fi

if test -z "$OBS_SCHEDULER_ARCHITECTURES" ; then
	echo "WARNING: no scheduler architectures configured, falling back to i586"
	OBS_SCHEDULER_ARCHITECTURES=i586
fi

bsuser=`perl -I/usr/lib/obs/server -MBSConfig -e 'print ( $BSConfig::bsuser || "obsrun" )'`
bsgroup=`perl -I/usr/lib/obs/server -MBSConfig -e 'print ( $BSConfig::bsgroup || "obsrun" )'`

case "$1" in
	start)
		mkdir -p "$rundir" "$logdir"
		chown $bsuser:$bsgroup "$logdir" "$rundir"
		cd "$obsdir"
                # FIXME: not nice, this should receive a proper daemon handling, 
                #        including real logging, pid file and startproc
		for i in $OBS_SCHEDULER_ARCHITECTURES; do
			if ! test -e "$logdir"/scheduler_$i.log; then
				touch "$logdir"/scheduler_$i.log
				chown $bsuser:$bsgroup "$logdir"/scheduler_$i.log
			fi
		        $OBS_SCHEDULER_WRAPPER ./bs_sched $i >> "$logdir"/scheduler_$i.log 2>&1 &
		done
	;;
	stop)
		$obsdir/bs_admin --shutdown-all-schedulers 600
		test $? != 2 || pkill bs_sched 
	;;
	*)
		echo "Usage: $0 {start|stop}"
		exit 1
	;;
esac
