#!/bin/sh
# this script should add a user under chroot environment
# WARNING: due to a writing manner, used for this script, it cannot be 
# ported to another host by changing variables only. You should look 
# at the code & change some 1st.
# (c) Light Olli, license is GNU like.

if [ ! -n "$1" ]; then
  echo "Require username as parameter".
  exit 1
fi

if [ -n "$2" ]; then
  echo "This script accepts only one parameter."
  exit 1
fi

# variables
chrootdir="/users/userchroot"
ChrootEtc="$chrootdir/etc"
chrootadduserutil="/usr/sbin/adduser"
chrootpasswdutil="/usr/bin/passwd"
chrootmkdirutil="/bin/mkdir"
chrootchmodutil="/bin/chmod"
chrootchownutil="/bin/chown"

##### start work
# adding mirror user for chroot one for quotas.
echo "Adding a mirror-user upper chroot 1st for quotas."
echo "Don't forget to check that chroot & nonchroot uids are the same."
chattr -i /etc
chattr -i /etc/shadow* /etc/passwd* /etc/gshadow* /etc/group* /etc/.pwd.lock
adduser -M -g chrooted -d /dev/null -n -s /bin/false -c "Chrooted user copy for quotas" $1
chattr +i /etc/shadow* /etc/passwd* /etc/gshadow* /etc/group* 
# adding chroot user
chattr -R -i $ChrootEtc
chroot $chrootdir $chrootadduserutil $1
echo -e "The following is mashine-generated password for $1.\n"
#(cat /dev/random 2>&1| head -c 8 2>&1|mimencode -b) 2>&1|head -1
/etc/bin/system/passwd-gen
echo -e "\n"
chroot $chrootdir $chrootpasswdutil $1
chroot $chrootdir $chrootchmodutil 750 /home/$1 /home/$1/public_html /home/$1/cgi-bin 
chroot $chrootdir $chrootchownutil .apache /home/$1 /home/$1/public_html /home/$1/cgi-bin 
echo -e "\nWaring - this script doesn't sets virtual hosts for apache."
echo "After creating virtual host for apache, don't forget to give rights for logs."
echo "This should be somthing like:"
echo -e "\tchmod 750 $chrootdir/var/log/apache/[virtualhost]"
echo -e "\tchroot $chrootdir chown .$1 /var/log/apache/[virtualhost]\n"
##### end work
chattr -R +i $ChrootEtc/*
exit 0
#EOF