#!/bin/sh

TGT=''
if [ -e /targets/links/scratchbox.config ] ; then
	. /targets/links/scratchbox.config
	TGT=$SBOX_TARGET_DIR
fi

USERN="user"
GROUPN="users"
USERID="29999"
GROUPID="29999"
UHOME="$TGT/home/$USERN"

week=`date +%V`

update-rc.d x-server.sh start 21 2 3 4 5 . stop 23 0 1 6 .
update-rc.d ttyusb0 start 99 2 .

rm -f $TGT/etc/hostname

echo 'Making volatile dirs symlinks to /tmp'
rm -rf $TGT/var/log
if [ ! -d $TGT/var/log ] 
then
	mkdir -p $TGT/var/log
fi

mkdir -p /media/mmc1 

#ln -s /tmp/run $TGT/var/run
#ln -s /tmp $TGT/var/tmp
#ln -s /tmp $TGT/var/log
hostname="Nokia770-$week"
btname="Nokia 770"

#rm -f $TGT/etc/mtab
#ln -s /proc/mounts $TGT/etc/mtab

echo $hostname > $TGT/etc/hostname

if [ -e $TGT/etc/hosts ]
then
	temphosts="$TGT/etc/hosts.$RANDOM"
	sed -e "/^127.0.0.1\s/ s/^.*$/127.0.0.1 $hostname localhost/" $TGT/etc/hosts > $temphosts
	mv $temphosts $TGT/etc/hosts
else
	echo "127.0.0.1 $hostname localhost" > $TGT/etc/hosts
fi

# SIGH, we can't add dirs to /home in scratchbox
# We don't want adduser on our system:

echo "setting root password and adding $USERN/messagebus (sigh)"

/usr/sbin/usermod -p SU.odxvRwp3Vs root

if getent group dialout > /dev/null 2>&1 ; then :; else
	if getent group 20 > /dev/null 2>&1 ; then :; else
		/usr/sbin/groupadd -g 20 dialout
	fi
fi

if getent group $GROUPN > /dev/null 2>&1 ; then 
	groupid=`getent group $GROUPN | cut -d: -f3`
	if echo "$groupid" | grep -q "$GROUPID" ; then :; else
		if getent group $GROUPID > /dev/null 2>&1 ; then
			echo "there is an old group $GROUPN ... deleting ..."
			groupdel $GROUPN
			echo "there is a group with gid $GROUPID ... changing ..."
			groupmod -n $GROUPN `getent group $GROUPID | cut -d: -f1`
		else
			echo "the group id is not $GROUPID ... changing ..."
			groupmod -g $GROUPID $GROUPN
		fi
	fi
else
	if getent group $GROUPID > /dev/null 2>&1 ; then
		groupname=`getent group $GROUPID | cut -d: -f1`
		echo "the group is not called $GROUPN ... renaming ..."
		groupmod -n $GROUPN $groupname
	else
		/usr/sbin/groupadd -g $GROUPID $GROUPN
	fi
fi

if getent passwd $USERN > /dev/null 2>&1 ; then :; else 
	if getent passwd $USERID > /dev/null ; then
		userid29999=`getent passwd $USERID | cut -d":" -f1`
		echo "the user is not called $USERN ... renaming..."
		# we might want to copy the old files the user owns to the new place... if any
		#userid29999home=`getent passwd 29999 | cut -d":" -f6`
		usermod -l $USERN -d /home/$USERN -u $USERID $userid29999
	else
		/usr/sbin/useradd -g $GROUPN -u $USERID -G dialout -d /home/$USERN -s /bin/sh $USERN
	fi
fi

mkdir -p /etc/bluetooth/
echo $btname > $TGT/etc/bluetooth/name

#/usr/sbin/usermod -p SU.odxvRwp3Vs user 

[ ! -d $UHOME ] && mkdir -p $UHOME
chown $USERID:$GROUPID $UHOME
chmod 750 $UHOME

if getent passwd messagebus > /dev/null 2>&1 ; then :; else
	/usr/sbin/groupadd messagebus
	/usr/sbin/useradd -g messagebus -G dialout -d /var/run/dbus -s /bin/false messagebus
fi
#shadowconfig on

