#!/bin/ash
# make a new user, adding it to the right groups and create user home dir from template
# jamesbond 2012
#
# $1-new user name, fail if user already exist, $2-home directory
# Note: no password is assigned to the user - this must be done separately

### configuration
. $BOOTSTATE_PATH
HOME_TEMPLATE=${BASE_SFS_MOUNT}/root			# template for home directory: /aufs/pup_ro/root
HOME_DIR=/home/$1								# location of home directory
STD_GROUPS="users tty audio video lp lpadmin"	# list of groups to include the new user in
FILE_MODE=${FILE_MODE:-640}
DIR_MODE=${DIR_MODE:-2750}

### main
if [ $(id -u) -ne 0 ]; then
	echo "Must run as root."
	exit
fi
if [ $# -eq 0 ]; then
	echo "Usage: mkuser.sh user [home-dir]"
	exit
fi

[ $2 ] && HOME_DIR=$2
if busybox adduser -D -h $HOME_DIR $1; then
	# add to the right groups
	for p in $STD_GROUPS; do
		busybox addgroup $1 $p
	done
	
	# copy files from template dir - don't copy anything to do with spot, Downloads, Fonts, and Desktop 
	if cd $HOME_TEMPLATE 2>/dev/null; then
		find . | grep -Ev "spot|^\./Downloads|^\./Fonts|^\./Desktop|^\./\.packages" | cpio -dp $HOME_DIR 2> /dev/null
	else
		# can't go to aufs /root, copy minimal stuff needed
		if cd /root; then
			cp -a .config .dbus .fatdog .gtkrc* .icons .local .sven \
				.xinitrc .xserverrc .Xresources Startup Choices \
				$HOME_DIR
			mkdir -p $HOME_DIR/.cache
		else 
			# can't even access /root, just setup symlinks and standard directories
			cd $HOME_DIR
			ln -sf /etc/X11/xinitrc .xinitrc
			ln -sf /etc/X11/xserverrc .xserverrc
			mkdir -p Startup .config .local .cache
		fi
	fi
	chown -Rh $1:$1 $HOME_DIR
	find $HOME_DIR -type f -print0 | xargs -0 chmod $FILE_MODE
	find $HOME_DIR -type d -print0 | xargs -0 chmod $DIR_MODE

	echo done.
fi
