#!/bin/sh
#
# pld-builder	perform adminstrator's tasks for PLD Linux Builder
#
# chkconfig:	345 99 01
#
# description:	perform adminstrator's tasks for PLD Linux Builder
#
# $Id: pld-builder.init,v 1.12 2010/07/08 10:50:54 glen Exp $

# Source function library
. /etc/rc.d/init.d/functions

# Defaults
CHROOTS=

# Get service config - may override defaults
[ -f /etc/sysconfig/pld-builder ] && . /etc/sysconfig/pld-builder

mount_chroots() {
	# mount /proc in chroots
	local ret
	for CHROOT in $CHROOTS; do
		show "chroot: %s mount /proc" "$CHROOT"
		ret=$(chroot $CHROOT mount /proc > /dev/null 2>&1; echo $?)
		[ $ret -eq 0 ] && ok || fail
	done
}

umount_chroots() {
	local ret
	for CHROOT in $CHROOTS; do
		show "chroot: %s umount /proc" "$CHROOT"
		ret=$(chroot $CHROOT umount /proc > /dev/null 2>&1; echo $?)
		[ $ret -eq 0 ] && ok || fail
	done
}

chroots_status() {
	local ret
	for CHROOT in $CHROOTS; do
		show "chroot: %s is /proc mounted?" "$CHROOT"
		ret=$(chroot $CHROOT mount 2> /dev/null | grep -q 'none.*/proc'; echo $?)
		[ $ret -eq 0 ] && ok || fail
	done
}

start() {
	# Check if the service is already running?
	if [ -f /var/lock/subsys/pld-builder ]; then
		msg_already_running "PLD Linux Builder"
		return
	fi

	if [ -z "$CHROOTS" ]; then
		# no chroots configured. return and be silent
		return
	fi
	msg_starting "PLD Linux Builder"
	busy; echo
	mount_chroots
	RETVAL=$?
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/pld-builder
}

stop() {
	if [ ! -f /var/lock/subsys/pld-builder ]; then
		msg_not_running "PLD Linux Builder"
		return
	fi

	# Stop daemons.
	msg_stopping "PLD Linux Builder"
	busy; echo
	umount_chroots
	rm -f /var/lock/subsys/pld-builder >/dev/null 2>&1
	RETVAL=0
}

condrestart() {
	if [ ! -f /var/lock/subsys/pld-builder ]; then
		msg_not_running "PLD Linux Builder"
		RETVAL=$1
		return
	fi

	stop
	start
}

# See how we were called.
case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  restart)
	stop
	start
	;;
  try-restart)
	condrestart 0
	;;
  force-reload)
	condrestart 7
	;;
  status)
	chroots_status
	RETVAL=$?
	;;
  *)
	msg_usage "$0 {start|stop|restart|try-restart|force-reload|status}"
	exit 3
	;;
esac
exit $RETVAL
