#!/bin/bash


# TODO: 20090904 winex: add checking already mounted dir inside chroot


INC=/usr/share/ltsp/diskless-functions
. "$INC" || exit 16


[[ -z $1 ]] && {
	echo "Usage: $PROG CHROOT [-k|--keep-mounts] [--nb|--no-bindmount] [--home] [COMMAND]..." >&2
	exit 1
}

ROOT_DIR=`dirname "$1"`
ROOT_NAME=` basename "$1"`
ROOT_REAL="$ROOT_DIR/$ROOT_NAME"
ROOT="$ROOT_DIR/__live__.$ROOT_NAME"
UNMOUNT=yes
BINDMOUNT=yes
MOUNTHOME=
shift


echo_header "Starting $PROG..."
echo_col blue "#### CHROOT: $ROOT"
[ -n "$*" ] && echo_col blue "####   ARGS: $@"


# parse options
while [[ -n $1 ]]; do
	case $1 in
	-k|--keep-mounts)
		UNMOUNT=no
		shift
		;;
	--nb|--no-bindmount)
		BINDMOUNT=no
		ROOT=$ROOT_REAL
		shift
		;;
	--home)
		MOUNTHOME=yes
		shift
		;;
	*)
		break
		;;
	esac
done


mount_stuff()
{
	[[ -z $1 ]] && {
		error "must specify CHROOT argument"
		exit 3
	}
	[[ $BINDMOUNT == "yes" ]] && {
		action "bind-chroot: mounting..." mount -o bind --make-rslave "$ROOT_REAL" "$1"
	}

	action "mounting proc..."   mount --make-slave -t proc proc "$1/proc"
	action "mounting sys..."    mount --make-slave -t sysfs sysfs "$1/sys"
	action "mounting devpts..." mount --make-slave -t devpts devpts "$1/dev/pts"
	#action "mounting devshm..." mount --make-slave -t tmpfs tmpfs "$1/dev/shm"
	#action "mounting tmpfs..."  mount --make-slave -t tmpfs tmpfs "$1/tmp"

	# optional
	# when using systemd, see: https://wiki.debian.org/systemd#Installing_without_systemd
	action "mounting mnt/zealot..." mount -o bind --make-rslave /mnt/zealot "$1/mnt/zealot"
	[[ $MOUNTHOME == "yes" ]] && action "mounting home from STATES/$ROOT_NAME..." mount -o bind --make-rslave "$ROOT_DIR/../../homeless/$ROOT_NAME" "$1/home"
}

umount_stuff()
{
	[[ -z $1 ]] && {
		error "must specify CHROOT argument"
		return
	}

	action "unmounting everything i've mounted..."
	umount "$1/home" 2>/dev/null
	umount "$1/mnt/zealot" 2>/dev/null
	#umount "$1/tmp" 2>/dev/null
	#umount "$1/dev/shm" 2>/dev/null
	umount "$1/dev/pts" 2>/dev/null
	umount "$1/sys" 2>/dev/null
	umount "$1/proc" 2>/dev/null

	[[ $BINDMOUNT != "yes" ]] && return

	action "bind-chroot: unmounting..." umount "$1" 2>/dev/null
}

cleanup()
{
	[[ $BINDMOUNT != "yes" ]] && return 0
	action "bind-chroot: removing directory..." rmdir "$1" 2>/dev/null
}


valid_chroot "$ROOT_REAL" || {
	error "$ROOT_REAL: not a valid chroot"
	exit 2
}

[[ $BINDMOUNT == "yes" ]] && action "bind-chroot: creating directory..." mkdir -p "$ROOT"

umount_stuff "$ROOT"
mount_stuff "$ROOT"
[[ $BINDMOUNT == "yes" ]] && {
	valid_chroot "$ROOT" || {
		error "$ROOT: not a valid chroot, something is wrong here!"
		cleanup "$ROOT"
		exit 4
	}
}


# perform chroot itself
export CHROOT="${ROOT_DIR##*/}/${ROOT##*/}"
export debian_chroot="$CHROOT"
action "chrooting..." /usr/sbin/chroot "$ROOT" "$@"

[[ $UNMOUNT == "yes" ]] && umount_stuff "$ROOT"

cleanup "$ROOT"
action "DONE!"
echo
