#!/bin/bash

ME="$0"
if [ -h "$0" ] ; then
	ME=`readlink -f "$0"`
fi

sbinpath=`dirname "$ME"`
if [ "z$sbinpath" = 'z.' ] ; then
	sbinpath=`pwd`
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

SBOX_CONF="${SBOX_DIR}/etc/scratchbox-configuration"
if [ -r "$SBOX_CONF" ] ; then
	source "$SBOX_CONF"
fi

start_sbox()
{
	echo -n "Starting Scratchbox: "

	local START_OPTIONS=
	if [ "z$SBOX_CONF_BIN_W32" != 'z1' ] ; then
		START_OPTIONS='-w'
	fi

	$SBOX_DIR/sbin/register_misc_runner $START_OPTIONS && 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
