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

#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 [ ! -d "$CHROOT/etc/" ] ; then
  echo "Nothing to do; chroot not mounted!"
  exit 1
fi

echo "Closing the chroot... Killing chroot apps"

fuser -m "$CHROOT" -k

echo "..Unmounting bound dirs..."

umount "$CHROOT/home/user"

#Any external devices
MNTD=`cat /proc/mounts | grep ' $CHROOT/media/' | awk '{print $2}'`
for MDRV in $MNTD ; do
  umount -l "$MDRV"
done

umount -l "$CHROOT/var/tmp"
umount -l "$CHROOT/tmp"
umount -l "$CHROOT/dev/pts"
umount -l "$CHROOT/proc"
umount -l "$CHROOT/dev"

echo "..Unmounting chroot.."
umount -ld "$CHROOT"

if [ ! "x" = "x`grep device-mapper /proc/misc`" ] ; then
  if [ -e "/dev/dm-0" ] ; then
    echo "..Unmounting turbo loop.."
    dmlosetup -d /dev/loop0
  fi
fi

echo "chroot closed."
exit 0