#!/bin/bash
#
# Copyright 2007,2008,2009,2012,2014 Bernie Innocenti <bernie@codewiz.org>
#
# Launches a fully functional environment from another Linux partition.
#
# For increased interoperability with the host system, add this line
# to your /etc/sudoers:
#   Defaults env_keep += "CHROOT SSH_AUTH_SOCK DBUS_SESSION_BUS_ADDRESS DISPLAY XAUTHORITY"
#

if [ $# -ne 1 ] ; then
	echo "Usage: $0 {NEWROOT}"
	exit 1
fi

if [ `id -u` -ne 0 ]; then
	exec sudo -i $0 "$@"
fi

NEWROOT=`readlink -e $1`
PATH=/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin

if ! [ -d "$NEWROOT" ]; then
	echo >2 "$NEWROOT must exist"
	exit 1
fi

[ -d "$NEWROOT/etc" ] || mount "$NEWROOT" || exit 1

BIND_DIRS="
	/proc
	/sys
	/dev
	/dev/pts
	/dev/shm
	/tmp
	/home
	/run
	/boot/efi
	/etc/machine-id
"

for dir in $BIND_DIRS; do
	[ ! -e $dir ] && continue
	# Recursively bind everything under $dir to the new root, and make it
	# a "slave mount" so we can unmount it with all its sub-mounts.
	mount --rbind --make-rslave "$dir" "$NEWROOT$dir"
done

if [ -z "$XAUTHORITY" ] && [ -f "$HOME/.Xauthority" ]; then
	XAUTHORITY="$HOME/.Xauthority"
	export XAUTHORITY
fi

if [ -n "$XAUTHORITY" ] && [ "$XAUTHORITY" != "$HOME/.Xauthority" ]; then
	touch "$NEWROOT$HOME/.Xauthority"
	mount --bind "$XAUTHORITY" "$NEWROOT$HOME/.Xauthority"
	XAUTHORITY="$HOME/.Xauthority"
	export XAUTHORITY
	xauthority_bound=yes
fi

export CHROOT=`echo "$NEWROOT" | sed -e 's:\(^/\|/$\)::g' -e 's:/:_:g'`
chroot "$NEWROOT" $SHELL -l

[ "$xauthority_bound" = yes ] && umount "$NEWROOT$HOME/.Xauthority"

# unmount everything under $NEWROOT, in reverse order
cat /proc/mounts | awk '{print $2}' | grep "^$NEWROOT" | sort -r | xargs umount
