#!/bin/sh
#Close a mounted chroot; this means killing all the chroot apps and unmounting the bound directories.

# By Alan M Bruce (qole)
#
# GPL licensed; keep code free!

if [ "`whoami`" != "root" ] ; then
  echo "please run me as root!"
  exit 9
fi

#Try to get the chroot location from the first parameter
CHROOT=$1

#Try to get the chroot location from the config file... 
if [ "x$CHROOT" = x ] ; then
  #Pull in the config, if possible...
  [ -f /home/user/.chroot ] && . /home/user/.chroot
  #Still not set? Set to default
  [ "x$CHROOT" != x ] || CHROOT=/debian
fi

#Abort if chroot not mounted.
if [ ! -f "$CHROOT/var/lock/qmount-complete" ] ; then
  echo "Nothing to do; chroot not mounted!"
  exit 1
fi

echo "Closing the chroot..."

#

TEST1=`mount | grep " $CHROOT "`
if [ "x$TEST1" != "x" ] ; then
  echo "...Killing chroot apps..."
  fuser -m "$CHROOT" -k
else
  fuser "$CHROOT" -k
fi

echo "..Unmounting bound dirs..."

#Any external mounts

umount -fl $CHROOT/home/user/MyDocs
umount -fl $CHROOT/dev/pts

MNTD=`cat /proc/mounts | grep " $CHROOT/" | awk '{print $2}'`
for MDRV in $MNTD ; do
  echo "unmounting $MDRV"
  umount -l "$MDRV"
done

if [ -f "$CHROOT/var/lock/qmount-complete" ] ; then
  rm "$CHROOT/var/lock/qmount-complete"
fi

if [ -f "$CHROOT/var/lock/chroot-complete" ] ; then
  rm "$CHROOT/var/lock/chroot-complete"
fi

/sbin/qumount $CHROOT

echo "chroot closed."
exit 0