#!/bin/sh
# 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.
#
# This example implements local apps in ltsp
# For it to work, it should be placed at /usr/bin in the ltsp chroot
# with execution permissions
#


. /usr/share/ltsp/ltsp-common-functions

logit() {
    logger -t localapp -p daemon.info $1
}


if [ -z  "${LDM_USERNAME}" ]; then 
	LDM_USERNAME=$(cat $(ls -1 /var/run/ltsplogin*|head -1))
fi


if [ -z  "${LDM_HOME}" ]; then 
	LDM_HOME=$(cat $(ls -1 /var/run/ltsphome*|head -1))
fi

if [ -z  "${XAUTHORITY}" ]; then 
	XAUTHORITY=${LDM_HOME}/.Xauthority
fi


if [ -n "${LDM_USERNAME}" -a -n "$(/usr/bin/id ${LDM_USERNAME})" ]; then
    true
else
    logit "Unknown user:  $LDM_USERNAME"
    exit 1
fi



launch()
{	
		su - ${LDM_USERNAME} -c "DISPLAY=$DISPLAY PULSESERVER=$PULSE_SERVER XAUTHORITY=$XAUTHORITY ${1}" &

}


DISPLAY=:7.0
PULSE_SERVER=127.0.0.1:4713
# Make sure the local user has access to X
chown ${LDM_USERNAME} $XAUTHORITY


if [ ! -z "$1" ]; then
	launch "${1}"
	exit 0
fi

while :; do

	if [ -f ${LDM_HOME}/local.exec ]; then
		LTSP_COMMAND=$(head -1 ${LDM_HOME}/local.exec)
		rm -f ${LDM_HOME}/local.exec
		launch "${LTSP_COMMAND}"
	fi
	
	sleep 1     
done
