#!/bin/bash

# it's important to restrict the available binaries
# to only those that we need.  putting "/bin/sh"
# would make things easier for me, but disallowing
# a command interpreter provides some additional
# security 

BINARIES="ls sh scp"

function usage {
	echo $0: usage:
	echo 	$0 \<directory to setup for chroot\> \<user\>
	exit 1
}

function err {
	echo -e "\n\n\n$@\n"
	usage
}

function checkdir {
	if [ ! -d $1 ]; then 
		mkdir $1; 
	fi
}

function cond_copy {
	if [ "x$3" != "x" ]; then
		if [ ! -f $1$2 ]; then
			cp $3 $1$2
		fi
		return
	fi
	if [ ! -f $1/$2 ]; then
		cp $2 $1$2
	fi
}

if [ "x$1" = "x" ]; then
	usage
fi

if [ "x$2" = "x" ]; then
	usage
fi

TARGET=$1
USER=$2

echo "# Setting up a chrootable directory: $TARGET"
if [ ! -d $TARGET ]; then
	err $TARGET isnt a directory or does not exist!
	usage
fi

if [ "x$TARGET" = "x/" ]; then
    err $TARGET cant be root!
fi

echo "# creating a bunch of directories, some of which probably aren't needed"
checkdir $1/usr
checkdir $1/lib
checkdir $1/usr/lib
checkdir $1/usr/lib/ssh
checkdir $1/bin
checkdir $TARGET/etc
checkdir $TARGET/pub

# $CHBINDIR is for convenience, if you change it, this
# script breaks.  this is lame.
CHBINDIR=/bin/
echo "# copying neccesary binaries in"
for bin in $BINARIES; do
	destbinpath=$CHBINDIR$bin
	srcbinpath=`which $bin | grep -v ^alias`
	fullpath_list="$srcbinpath $fullpath_list"
	if [ ! -f $TARGET/$destbinpath ]; then
		cond_copy $TARGET $destbinpath $srcbinpath
	fi
done
echo "# copying libraries in"
LIB_LIST=`ldd $fullpath_list 2> /dev/null | cut -f2 -d\> | cut -f1 -d\( | grep "^ " | sort -u`
LIB_LIST="$LIB_LIST /lib/libnss_files-2*.so /lib/libnss_files.so.2"
if [ "x$LIB_LIST" != "x" ]; then
	for lib in $LIB_LIST; do
		if [ ! -f $TARGET/$lib ]; then
			cond_copy $TARGET $lib
		fi
	done
fi

cond_copy $TARGET /usr/lib/ssh/sftp-server

echo "# copying passwd database and group file in"

if [ ! -f $TARGET/etc/passwd ]; then
	cat /etc/passwd |grep $USER > $TARGET/etc/passwd
fi

if [ ! -f $TARGET/etc/group ]; then
    cat /etc/group | grep `cat /etc/passwd | grep $USER | awk -F: '{print $4}'` > $TARGET/etc/group
fi
chown $USER $TARGET/pub

exit 0
