#!/bin/sh

. /usr/share/ltsp/ltsp_config

tty=$(tty)
case "$tty" in
	/dev/tty*) # with udev (2.6 kernel)
        ttynum=${tty#/dev/tty}
        ;;
    /dev/vc/*) # with devfs (2.4 kernel)
        ttynum=${tty#/dev/vc/}
        ;;
esac

displaynum=$(($ttynum - 1))

MAX_TIMEOUT=30
MAX_COUNT=5
COUNTER=0
FLAG=1

ARGS=""

if [ -n "${X_CONF}" ]; then
    ARGS="${ARGS} -config ${X_CONF}"
fi

while [ $FLAG -ne 0 ]; do
    START_TIME=$(date +%s)
    NX_OUTPUT=`xinit /usr/share/ltsp/screen.d/start_nx -- :$displaynum vt${ttynum} ${ARGS} 2>&1 | grep '^ERROR:'`
    FINISH_TIME=$(date +%s)
    TIMEOUT=$((FINISH_TIME-START_TIME))

    if [ $TIMEOUT -le $MAX_TIMEOUT ]; then
        if [ $COUNTER -ge $MAX_COUNT ]; then
            COUNTER=0
#            Message nxclient "$RDESKTOP_OUTPUT" || FLAG=0
        else
            COUNTER=$((COUNTER+1))
        fi
    else
        COUNTER=0
    fi
done

