#!/bin/sh
# Chroots and runs a shell or any command as non-root.

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

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

if [ "$#" -lt "2" ] ; then
  echo "You need at least 2 parameters:"
  echo "    filesystem-location and mountpoint"
  exit 9
fi

IMGFILE=$1
shift 1

CHROOT=$1
shift 1

# If CHROOTUSER is set, use it. 
# Otherwise fall back on current user
[ "x$CHROOTUSER" != x ] || CHROOTUSER=`whoami`

#Note use of su below, so no chroot-side script req'd to drop privileges.
#With no args, use a shell; su will get the right one, with no -c
#With args, just run them as $CHROOTUSER.
if [ $# = 0 ] ; then
  echo As $CHROOTUSER, starting chroot shell...
  sudo /sbin/qchroot $IMGFILE $CHROOT su $CHROOTUSER
else
  echo As $CHROOTUSER, starting chroot $1
  sudo /sbin/qchroot $IMGFILE $CHROOT su $CHROOTUSER -c "$*"
fi
