#!/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`

FAILED=false

realpath()
{
	readlink -f $1 2> /dev/null
	return $?
}

is_mounted()
{
	local path=`realpath $1`
	if [ x"$path" != x ]; then
		mount | grep "on $path type" > /dev/null
		return $?
	fi
	return 1
}

do_umount()
{
	if is_mounted $1; then
		umount `realpath $1`
		if [ $? -ne 0 ]; then
			FAILED=true
			return
		fi

		if is_mounted $1; then
			FAILED=true
			return
		fi

		# Be paranoid about it...
		if [ "`find $1/ -mindepth 1 | wc -l`" -ne 0 ]; then
			FAILED=true
		fi
	fi
}

if [ x"$1" = x ] ; then
	echo "Usage: $0 <username>" 1>&2
	exit 1
fi

ROOT=$SBOX_DIR/users/$1
if [ ! -d $ROOT ]; then
	echo "User $1 does not have a Scratchbox user account!" 1>&2
	exit 1
fi

do_umount $ROOT/sys
do_umount $ROOT/dev/shm
do_umount $ROOT/dev/pts
do_umount $ROOT/dev
do_umount $ROOT/proc
do_umount $ROOT/tmp
do_umount $ROOT/scratchbox

if $FAILED; then
	echo 1>&2 "  -------------------------------------------------------------------"
	echo 1>&2 "    WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING"
	echo 1>&2 "  -------------------------------------------------------------------"
	echo 1>&2 "      Trouble umounting!  Some mounts could still be active!"
	echo 1>&2 "      Removing the scratchbox or user directories can damage your"
	echo 1>&2 "      system if the mounts are still active!"
	echo 1>&2 "  -------------------------------------------------------------------"
	exit 1
fi

exit 0
