# Copyright (C) 2008 José L. Redrejo Rodríguez, jredrejo at-no-spam debian.org.
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
#for this to work, previously, directory /etc must be writtable on the
# ltsp chroot . When using nfs in ltsp, that can be achieve just adding
# /etc to the list of the copy_dirs variable in /etc/default/ltsp-client-setup
#
# "useradd ltsp -d /var/tmp/ltsp -g fuse -u 65533"
# Also, very imporant, sshfs package has to be version >=2.0-1
# with Debian #430225 fixed, otherwise this won't work

set -e
if [ -f /usr/share/ltsp/ltsp-common-functions ]; then
    . /usr/share/ltsp/ltsp-common-functions
else
    # backwards compatibility for older ltsp versions
    . /usr/share/ldm/ltsp-common-functions
fi

DEFAULTGROUPS="adm dialout cdrom floppy audio dip video plugdev scanner fuse lpadmin admin netdev"
LOGIN=$(ssh -S $LDM_SOCKET $LDM_SERVER "id -un")
LOCAL_UID=$(ssh -S $LDM_SOCKET $LDM_SERVER "id -u")
LOCAL_GID=$(ssh -S $LDM_SOCKET $LDM_SERVER "id -g")
LOCAL_GROUP=$(ssh -S $LDM_SOCKET $LDM_SERVER "id -gn")

if [ -z "$LOGIN" ]; then
	exit 1
fi
echo $LOGIN>/var/run/ltsplogin$LDM_SERVER

groupadd -g ${LOCAL_GID}  ${LOCAL_GROUP} 

useradd ${LOGIN}  -s /bin/bash -m  -d /var/tmp/${LOGIN}  -g ${LOCAL_GID}  -u ${LOCAL_UID} 


for each_group in $DEFAULTGROUPS; do
	adduser  ${LOGIN} $each_group >/dev/null 2>&1 ||true
done


#here comes the magic:
sshfs -o nonempty,uid=${LOCAL_UID},gid=${LOCAL_GID},allow_other,ControlPath=${LDM_SOCKET}   ${LDM_SERVER}: /var/tmp/${LOGIN}


/usr/bin/localapp &
PID=$!
echo $PID > /var/lock/localapps
