#!/bin/sh

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

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

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

if [ -z "$DISPLAY" ];then 
    logit "Unknown DISPLAY"
    exit 1
fi

# Initialize LTSP_COMMAND as blank
reset_xprop(){
    xprop -root -f $1 8s -set $1 ""
}

reset_xprop LTSP_COMMAND
reset_xprop LTSP_COMMAND_WAIT

# Make sure the local user has access to X
chown ${LDM_USERNAME} $XAUTHORITY

if boolean_is_true "$SOUND" ; then
    PULSE_SERVER="PULSE_SERVER=127.0.0.1"
fi

# Poll for LTSP_COMMAND changes and execute
while :; do
    LTSP_COMMAND="$(xatomwait LTSP_COMMAND)"
    [ "$?" != 0 ] && exit 

    LTSP_COMMAND=$(echo "${LTSP_COMMAND}"|sed -e 's/^LTSP_COMMAND = //' -e 's/^"//' -e 's/"$//')
    LTSP_COMMAND_WAIT=$(xprop -root -notype LTSP_COMMAND_WAIT |sed -e 's/^LTSP_COMMAND_WAIT = //' -e 's/^"//' -e 's/"$//')
    if [ -n "${LTSP_COMMAND}" ]; then
        # If LOCAL_APPS_APPS_WHITELIST is defined, reject anything not listed.  Otherwise allow by default.
        if [ -n "${LOCAL_APPS_WHITELIST}" ]; then
            unset TEMP_ALLOW_EXEC
            for cmd in $LOCAL_APPS_WHITELIST; do
                if [ "$cmd" = "$(echo $LTSP_COMMAND|cut -d\  -f1)" ]; then
                    TEMP_ALLOW_EXEC=1
                    break
                fi
            done
            if [ -z "${TEMP_ALLOW_EXEC}" ]; then
                logit "Rejecting command not listed in LOCAL_APPS_WHITELIST: $LTSP_COMMAND"
                reset_xprop LTSP_COMMAND
                reset_xprop LTSP_COMMAND_WAIT
                continue
            fi
        fi
    
        logit "Executing command as username ${LDM_USERNAME}: ${LTSP_COMMAND} "
        if [ "$LTSP_COMMAND_WAIT" = "true" ]; then
            su - ${LDM_USERNAME} -c "LANG=$LANG DISPLAY=$DISPLAY $PULSE_SERVER XAUTHORITY=$XAUTHORITY ${LTSP_COMMAND}"
        else
            su - ${LDM_USERNAME} -c "LANG=$LANG DISPLAY=$DISPLAY $PULSE_SERVER XAUTHORITY=$XAUTHORITY ${LTSP_COMMAND}" &
        fi
    fi
    reset_xprop LTSP_COMMAND
    reset_xprop LTSP_COMMAND_WAIT
done
