#!/bin/bash

CHROOTHOME=$1
CHROOTMOUNT=$2
USERNAME=$3
HOMEPATH=$4
SERVER=$5
CREDENTIALS=$6

DIRS="bin lib lib64 usr etc var dev proc"
RUNDIRS="run/samba"
MISCDIRS="shared search"

function usage()
{
	echo "Usage: mountchroot <chroot home> <chroot mount> <username> <homepath> <samba server> <credentials file name>"
	echo "Example: mountchroot /home/linux /var/tmp user /home/LIBREWORK/user lxserver /tmp/creds"
	exit 1
}

if [ -z "${SERVER}" ]
then
	usage
fi

if [ -n "$7" ]
then 
	usage
fi

for i in ${DIRS} ${RUNDIRS}
do
	MOUNTED=`mount | grep "${CHROOTMOUNT}/mnt.${USERNAME}/$i"`
	if [ -n "${MOUNTED}" ]
	then
		umount ${CHROOTMOUNT}/mnt.${USERNAME}/$i
	fi
done

MOUNTED=`mount | grep "${CHROOTMOUNT}/mnt.${USERNAME}${HOMEPATH}"`
if [ -n "${MOUNTED}" ]
then
	umount ${CHROOTMOUNT}/mnt.${USERNAME}${HOMEPATH}
fi

rm -rf ${CHROOTMOUNT}/mnt.${USERNAME}/tmp
mkdir -p ${CHROOTMOUNT}/mnt.${USERNAME}/tmp

for i in ${MISCDIRS}
do
	mkdir -p ${CHROOTMOUNT}/mnt.${USERNAME}/${i}
	chown ${USERNAME} ${CHROOTMOUNT}/mnt.${USERNAME}/${i}
	chmod 700 ${CHROOTMOUNT}/mnt.${USERNAME}/${i}
done

chown ${USERNAME} ${CHROOTMOUNT}/mnt.${USERNAME}
chmod 700 ${CHROOTMOUNT}/mnt.${USERNAME}
chown root:root ${CHROOTMOUNT}/mnt.${USERNAME}/tmp
chmod 1777 ${CHROOTMOUNT}/mnt.${USERNAME}/tmp

for i in ${DIRS}
do
	mkdir -p ${CHROOTMOUNT}/mnt.${USERNAME}/$i
	chown root:root ${CHROOTMOUNT}/mnt.${USERNAME}/$i
	chmod 755 ${CHROOTMOUNT}/mnt.${USERNAME}/$i

	MOUNTED=`mount | grep "${CHROOTMOUNT}/mnt.${USERNAME}/$i"`
	if [ -z "${MOUNTED}" ]
	then
		if [ "$i" == "proc" ]
		then
			mount -t proc $i ${CHROOTMOUNT}/mnt.${USERNAME}/$i
		else
			mount --bind ${CHROOTHOME}/$i ${CHROOTMOUNT}/mnt.${USERNAME}/$i
		fi
	fi
done

for i in ${RUNDIRS}
do
	mkdir -p ${CHROOTMOUNT}/mnt.${USERNAME}/$i
	chown root:root ${CHROOTMOUNT}/mnt.${USERNAME}/$i
	chmod 755 ${CHROOTMOUNT}/mnt.${USERNAME}/$i

	MOUNTED=`mount | grep "${CHROOTMOUNT}/mnt.${USERNAME}/$i"`
	if [ -z "${MOUNTED}" ]
	then
		mount --bind /$i ${CHROOTMOUNT}/mnt.${USERNAME}/$i
	fi
done

mkdir -p ${CHROOTMOUNT}/mnt.${USERNAME}${HOMEPATH}
chown ${USERNAME} ${CHROOTMOUNT}/mnt.${USERNAME}${HOMEPATH}
chmod 755 ${CHROOTMOUNT}/mnt.${USERNAME}

MOUNTED=`mount | grep "${CHROOTMOUNT}/mnt.${USERNAME}${HOMEPATH}"`
if [ -z "${MOUNTED}" ]
then
	mount -t cifs -o iocharset=utf8,credentials=${CREDENTIALS},uid=${USERNAME} //${SERVER}/${USERNAME} ${CHROOTMOUNT}/mnt.${USERNAME}${HOMEPATH}
	rm -f ${CREDENTIALS}
fi

cat > /etc/schroot/chroot.d/${USERNAME} << EOF
[${USERNAME}]
description=${USERNAME} chroot environment
directory=${CHROOTMOUNT}/mnt.${USERNAME}
users=${USERNAME}
groups=users
root-groups=root
EOF
