#!/bin/bash

if [ -L "$0" ]; then
	realpath=`readlink "$0"`
	sbinpath=`dirname $realpath`
else
	sbinpath=`dirname $0`
fi
sboxrel=`dirname $sbinpath`
SBOX_DIR=`readlink -f $sboxrel`

for i in register_misc_runner sbox_mount_all sbox_umount_all ; do
	if ! [ -x $SBOX_DIR/sbin/$i ]; then
		echo "Scratchbox: $SBOX_DIR/sbin/$i is missing!"
		exit 1
	fi
done

start_sbox()
{
	echo -n "Starting Scratchbox: "
	$SBOX_DIR/sbin/register_misc_runner && echo -n "binfmt_misc, "
	$SBOX_DIR/sbin/sbox_mount_all       && echo -n "mount."
	echo
}

stop_sbox()
{
	echo -n "Stopping Scratchbox: "
	$SBOX_DIR/sbin/sbox_umount_all      && echo -n "umount, "
	$SBOX_DIR/sbin/register_misc_runner --deregister && echo -n "binfmt_misc."
	echo
}

case "$1" in
	start)
		start_sbox
		;;

	stop)
		stop_sbox
		;;

	restart)
		$0 stop
		$0 start
		;;

	*)
		echo "Usage: $0 {start|stop|restart}"
		exit 1
		;;
esac

exit 0
