#!/bin/bash
# upkg-chroot
#
# Changes into another root doing some necessary tasks
#
# Copyright (C) 2004-2006 Raffaele Sandrini, Jürg Billeter
#
# This file is part of Upkg (http://www.upkg.org).
#
# Upkg is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2
# as published by the Free Software Foundation.
#
# Upkg is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Upkg; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Authors:
#   Raffaele Sandrini <rasa at paldo dot org>
#   Jürg Billeter <juerg at paldo dot org>

function usage ()
{
	echo "$appname: Usage: $appname [--force] <chrootdir>"
}

appname=$(basename $0)

# argument parsing
opts=$(POSIXLY_CORRECT=1 getopt -u -n $appname -l "force,help" "fh" $*)
[ $? -ne 0 ] && { usage; exit 1; }
set -- $opts

force=0
for i in $*
do
	case $i in
	-f|--force)
		force=1
		shift
		;;
	-h|--help)
		usage
		exit 0;
		;;
	--)
		shift
		break
		;;
	esac
done

[ -z "$1" ] && { usage; exit 1; }
[ $force -ne 1 -a $UID -ne 0 ] && { echo "$appname: You should run $appname as root. Use --force to override this restriction."; exit 1; }

chrootdir="$1"
[ -d "$chrootdir" ] || { echo "$appname: chroot directory does not exist"; exit 1; }
[ -x "$chrootdir/bin/bash" ] || { echo "$appname: $1 does not contain '/bin/bash'"; exit 1; }

# set up chroot
mount --rbind --make-rslave /dev $chrootdir/dev
mount --rbind --make-rslave /proc $chrootdir/proc
mount --rbind --make-rslave /sys $chrootdir/sys

# copy useful files
[ -e "$chrootdir/etc/resolv.conf" ] && mv $chrootdir/etc/resolv.conf{,.upkg-chroot}
cp /etc/resolv.conf $chrootdir/etc/resolv.conf

# chroot stuff
echo "Entering chroot..."
chroot $chrootdir /bin/bash --login
echo "Returned from chroot"

# reconstruct old useful files
[ -e "$chrootdir/etc/resolv.conf.upkg-chroot" ] && mv $chrootdir/etc/resolv.conf{.upkg-chroot,}

# unmount everything mounted by us
umount -l $chrootdir/{dev,proc,sys}
