# 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


if [ -e /usr/bin/localapp ]; then

    # Set up local uids/gids

    LOCALAPPS_CACHE=/var/cache/ltsp-localapps
    mkdir -p ${LOCALAPPS_CACHE} 2>/dev/null

    # Cleanup 
    LOCALAPPSD_PIDFILE=/var/run/ltsp/localapp
    mkdir -p /var/run/ltsp 2>/dev/null
    [ -r "$LOCALAPPSD_PIDFILE" ] && LOCALAPPSD_PID=$(cat $LOCALAPPSD_PIDFILE)
    # Kill PID
    if [ -n "$LOCALAPPSD_PID" ]; then
        pkill -P $LOCALAPPSD_PID
        rm $LOCALAPPSD_PIDFILE
    fi

    # Copy /etc/passwd and /etc/group to cache if it does not exist (should only happen on first login)
    for i in passwd group; do
        if [ ! -e "${LOCALAPPS_CACHE}/${i}" ]; then
            cp /etc/${i} "${LOCALAPPS_CACHE}/${i}"
        else
            cp "${LOCALAPPS_CACHE}/${i}" /etc/${i}
        fi
    done

    # Get logged in username if not set
    [ -z "$LDM_USERNAME" ] && LDM_USERNAME=$(ssh -S ${LDM_SOCKET} ${LDM_SERVER} 'echo ${USER}')
    export LDM_USERNAME=${LDM_USERNAME}

    echo $LDM_USERNAME>/var/run/ltsplogin${LDM_SERVER}

    # Get passwd info *just* for that user
    ssh -S ${LDM_SOCKET} ${LDM_SERVER} "/usr/bin/getent passwd ${LDM_USERNAME}" >>/etc/passwd

    # Get all group info and copy to TMPGROUP
    ssh -S ${LDM_SOCKET} ${LDM_SERVER} "/usr/bin/getent group|egrep -v '[[:digit:]]....?:'" >>/etc/group
    # Now, some groups may have different gids on the server than the client chroot
    # So, let's prune out all the dups
    TMPGROUP="${LOCALAPPS_CACHE}/tmpgroup"
    gnames=""
    while read line; do
        gname=$(echo $line|cut -d: -f1)
        match=
        for e in $gnames; do
            if [ "$gname" = "$e" ]; then
                match=1
            fi
        done
        if [ -z "$match" ]; then
            echo "$line" >>${TMPGROUP}
            gnames="$gnames $gname"
        fi
    done </etc/group
    cp -f ${TMPGROUP} /etc/group
    rm -f ${TMPGROUP}
    chmod 644 /etc/group

    # Get the system groups that the user belongs to, so we can add him back in
    myGroups=$(ssh -S ${LDM_SOCKET} ${LDM_SERVER} /usr/bin/getent group|egrep "[,:]${LDM_USERNAME}(,|$)"|cut -d: -f1| tr '\n' ',' | sed -e 's/,$//g')
    if [ -n "$myGroups" ]; then
        usermod -G "$myGroups" "${LDM_USERNAME}"||true
    fi

    # Now, let's mount the home directory

    # First, make the mountpoint
    LDM_HOME=$(getent passwd ${LDM_USERNAME}|cut -d: -f6)
    mkdir -p ${LDM_HOME}
    export LDM_HOME=${LDM_HOME}
    echo $LDM_HOME>/var/run/ltsphome${LDM_SERVER}

    chown ${LDM_USERNAME} ${LDM_HOME}

    ## Maybe do this:
    ## export HOME=${LOCALAPPS_CACHE}

    # Mount the home directory
    sshfs -o nonempty,allow_other,ControlPath=${LDM_SOCKET} ${LDM_SERVER}:${LDM_HOME} ${LDM_HOME}

    #Launch the ltsp-localappsd to handle the apps
    (
    echo $! > $LOCALAPPSD_PIDFILE

    # if cups is installed in the chroot, use LDM_SERVER for printing
    [ -d "/etc/cups" ] && echo "ServerName ${LDM_SERVER}" > /etc/cups/client.conf||true

    /usr/bin/localapp

    # Clean up cups config
    [ -r "/etc/cups/client.conf" ] && rm -f /etc/cups/client.conf

    # Copy back passwd and group
    for i in passwd group; do
        cp "${LOCALAPPS_CACHE}/${i}" /etc/${i}
    done
    
    # Unmount sshfs and remove the mount dir
    fusermount -uqz ${LDM_HOME}
    rm -Rf ${LDM_HOME}
    rm $LOCALAPPSD_PIDFILE
    )&
fi
