#!/bin/bash
#Script originally posted on ltsp-developers ML by Veli-Matti Lintu
#modified by warren@redhat.com

#!/bin/bash

SESS_DISPLAY=1000

# XXX: We would need a better way to do this.
# This is racy and INSECURE.
# It writes to /tmp/.X11-unix/ which any user can write, and it is
# totally predictable because it is incremental.
# Even randomized it is unsafe and should not be shipped in any
# distribution.
while true
do
let TEST_DISPLAY=$SESS_DISPLAY+6000

if [ -f /tmp/.X${SESS_DISPLAY}-lock ]; then
let SESS_DISPLAY=$SESS_DISPLAY+1
continue
fi

if [ -f /tmp/.X11-unix/X${SESS_DISPLAY} ]; then
let SESS_DISPLAY=$SESS_DISPLAY+1
continue
fi

if nc -z 127.0.0.1 $TEST_DISPLAY 2>/dev/null
then
let SESS_DISPLAY=$SESS_DISPLAY+1
continue
fi

break
done

# Identify the specific entry in xauth that we want to copy
case "$DISPLAY" in
localhost*)
# ssh forwarded xauth proxy or local X server
REALDISPNUMBER="${DISPLAY##localhost:}"
# we need the two spaces after
XAUTHENTRY="unix:$(echo $REALDISPNUMBER | awk -F'.' '{print
$1}') "
;;
*)
# assume hostname or IP address
XAUTHENTRY="$DISPLAY"
;;
esac

KEY=$(xauth list | grep "$XAUTHENTRY"| awk '{print $3}')
PROTOCOL=$(xauth list | grep "$XAUTHENTRY"| awk '{print $2}')

### It turns out that the way it was grabbing keys from xauth was wrong.
### It was grabbing old stale keys because it was doing it in the same
### fashion as ldm's script, which grabs the wrong key in this case.
### I fixed that above, but then realized that we do not even want this
### key. We want a new key generated for nxagent... so the above should
### be ripped out.

KEY=`mcookie`
PROTOCOL=MIT-MAGIC-COOKIE-1
xauth remove :${SESS_DISPLAY}
xauth add :${SESS_DISPLAY} ${PROTOCOL} ${KEY}
ulimit -c unlimited
/usr/bin/nxagent :${SESS_DISPLAY} -D -auth ~/.Xauthority -nopersistent -noignore &
ulimit -c 0

# UGLY HACK: We need to properly detect that X is done launching before
# proceeding
# Normally you would wait for SIGUSR1 from the child process, but
# we can't do that in a shell script. Another approach is to run
# an X client in a loop.
if [ -x /usr/bin/setxkbmap ]; then
while true; do
#/usr/bin/setxkbmap 2> /dev/null
/usr/bin/xhost
RETVAL=$?
if [ $RETVAL -eq 1 ]; then
sleep 0.2
else
break
fi
done
fi

# But that didn't work! nxagent tells the X client that it is ready,
# but then proceeds to fail when gnome-session talks to nxagent.
# An arbitrary delay before gnome-session seems to solve this issue.

sleep 3
export REAL_DISPLAY=${DISPLAY}
DISPLAY=:${SESS_DISPLAY} /usr/bin/gnome-session
