#!/bin/bash

ME="$0"
if [ -h "$0" ] ; then
	ME=`readlink -f "$0"`
fi

sbinpath=`dirname "$ME"`
if [ "z$sbinpath" = 'z.' ] ; then
	sbinpath=`pwd`
fi

sboxrel=`dirname "$sbinpath"`

SBOX_DIR=`readlink -f $sboxrel`

LD_HACK="$SBOX_DIR/host_shared/lib/ld.so --library-path $SBOX_DIR/host_shared/lib"

. $SBOX_DIR/sbin/compatibility.sh
. $SBOX_DIR/etc/question_func.sh

function addusertogroup() {
	local user=$1
	local group=$2

	if [ -f /etc/debian_version ]; then
		# This can add user locally to a group
		# even when using network authentication
		adduser $user $group
	else
		# The adduser syntax doesn't work at least in RedHat
		# Sudo doesn't add /usr/sbin to PATH in RedHat
		PATH=$PATH:/usr/sbin usermod -G `id -G -n $1 | tr " " ","`,$group $user
	fi

	if [ "$?" != 0 ] ; then
		echo "ERROR: Adding user '$user' to group '$group'"
		exit 2
	fi
}

if [ ! -f $SBOX_DIR/.run_me_first_done ]; then
	echo "$SBOX_DIR/run_me_first.sh has not been run!"
	exit 1
fi

SB_GROUP=`cat $SBOX_DIR/.run_me_first_done`

if [ "x$1" = x ]; then
	echo "Usage: $0 <username> [<add to group>=yes|no]"
	exit 1
fi

if ! getent passwd $1 &> /dev/null; then
	echo "User $1 does not exist in the system, aborting."
	exit 1
fi

umask 0022

mkdir -p $SBOX_DIR/users

if [ -d $SBOX_DIR/users/$1 ]; then
	echo "Scratchbox user account for user $1 already exists!"
	exit 1
fi

addtogrp="$2"

# Normal mode
if [ ! -f $SBOX_DIR/.sudo_mode ]; then
	if [ `id -u` != 0 ] ; then
		echo "This has to be run as root"
		exit 1
	fi

	GRPOK=no
	if getent group "$SB_GROUP" | cut -d : -f 4- | tr -d ' ' | grep -q "\(^\|,\)$1\(,\|$\)" ; then
		GRPOK=yes
	fi
		
	if [ "$GRPOK" = no ] ; then
		if [ x"$addtogrp" = x ]; then
			addtogrp=`question "Add user $1 to group '$SB_GROUP'?" 1 yes`
		fi
		if [ "$addtogrp" = yes ] ; then
			addusertogroup $1 $SB_GROUP
		fi
	fi

	(
	set -e
	
	mkdir $SBOX_DIR/users/$1
	$SBOX_DIR/sbin/sbox_mount $1

	cd $SBOX_DIR/users/$1

	tar xfz $SBOX_DIR/packages/sb_user_base.tar.gz
	for i in `tar tfz $SBOX_DIR/packages/sb_user_base.tar.gz`; do
		chown "$1:`id -g -n $1`" "$i" || exit 1
	done

	mkdir -p home/$1 targets/links host_usr/bin
	chown -R $1 home/$1 targets host_usr

	)

# Sudo mode
else
	(
	set -e
	
	mkdir $SBOX_DIR/users/$1
	cd $SBOX_DIR/users/$1
	tar xfz $SBOX_DIR/packages/sb_user_base.tar.gz

	mkdir -p home/$1 targets/links host_usr/bin

	)
fi

# Create links from sandbox root to target dir
for name in `cat $SBOX_DIR/etc/rootdirs`; do
	ln -sf /targets/links/$name $SBOX_DIR/users/$1/$name
done

echo "Scratchbox user account for user $1 added"
