#!/bin/sh

# Given a (non-existant) directory
# creates a chroot environment so users can login
# and have limited movements

# (c) 2002 Javier Fernandez-Sanguino Peņa <jfs@debian.org>

[ -z "$1" ] && {
	echo "Usage $0 directory"
	exit 1
}
id=`/usr/bin/id -u`

[ "$id" -gt 0 ] && 
	echo "WARNING: Needs to be run as root (for mknod to work)"

dir=$1

[  -e "$dir" ] && {
	echo "ERROR: $dir exists. Please specify a non-existant directory"
	exit 1
}

curdir=`/bin/pwd`
/bin/mkdir -p $dir
cd $dir
for i in bin dev lib home/test ; do 
	/bin/mkdir -p $i 
done

# Procedure:
# Hard link for files and just copy simbolyc links, 
# should work ok in the chroot

# Bin directory (minimal set of binaries)
for cmd in ls pwd true false rbash bash ; do
	if [ -f /bin/$cmd -a ! -L /bin/$cmd ] ; then
		/bin/ln /bin/$cmd bin/
	fi
	if [ -L /bin/$cmd ] ; then
		cp -a /bin/$cmd lib/
	fi
done

# Libraries (for previous binaries)
for lib in /lib/ld-linux* /lib/libc.* /lib/libdl* /lib/librt* /lib/ncurse* /lib/libpthread* ; do
	if [ -f $lib -a ! -L $lib ] ; then
		/bin/ln $lib lib/
	fi
	if [ -L "$lib" ] ; then
		cp -a $lib lib/
	fi
done

# Devices
cd dev
# We need as many tty's as consoles
/bin/mknod -m 644 tty1 c 4 1
/bin/mknod -m 644 tty2 c 4 2
/bin/mknod -m 644 tty3 c 4 3
/bin/mknod -m 644 tty4 c 4 4
/bin/mknod -m 644 tty5 c 4 5
/bin/mknod -m 644 tty6 c 4 6
# Some special nodes, just for fun
/bin/mknod -m 444 urandom c 1 9
/bin/mknod -m 666 zero c 1 5
/bin/mknod -m 666 null c 1 3
# Warning: since we do not have the /dev/log socket the
# 'debug' option of the PAM module will not work once chrooted

# Finish and get back were we started
cd $curdir

exit 0
