#!/bin/sh
HOME=/tmp

NX_SERVER=${NX_SERVER:-"$SERVER"}
NX_LINUX_USER=$HOSTNAME

NX_SERVER="$NX_SERVER:$NX_PORT"

MORE_WORDS=TRUE
while [ $# -gt 0 -a "$MORE_WORDS" ]; do
    case "$1" in
    -*|+*)
        MORE_WORDS=
        ;;
    *)
        NX_SERVER="$1"
        shift
        ;;
    esac
done

MORE_ARGS=TRUE
while [ $# -gt 0 -a "$MORE_ARGS" ]; do
    case "$1" in
    --admin|-a)
	NX_ADMIN="true"
	shift 1
	;;
    --session|-s)
	NX_SESSION="$2"
	shift 2
	;;
    --linux_user|-u)
	NX_LINUX_USER="$2"
	shift 2
	;;
    --desktop|-d)
	NX_DESKTOP="$2"
 	shift 2
	;;
    --link_speed|-l)
	NX_LINK_SPEED="$2"
	shift 2
	;;
    --cache_size|-c)
	NX_CACHE_SIZE="$2"
	shift 2
	;;

  *)
    MORE_ARGS=;;
  esac;
done;

NX_PORT=`echo $NX_SERVER|cut -d: -f2`
NX_SERVER=`echo $NX_SERVER|cut -d: -f1`
[ "$NX_PORT" == "$NX_SERVER" ] && NX_PORT=""

# copy NX config files and "known_hosts"
cp -rT /root/ /tmp/
[ ! -d /tmp/.nx/config ] && mkdir -p /tmp/.nx/config

# edit default session file
if [ -z $NX_SESSION ] ; then
    [ ! -e /tmp/.nx/config/terminal.nxs ] && cp /etc/ltsp/terminal.nxs /tmp/.nx/config/terminal.nxs
    NX_SESSION="/tmp/.nx/config/terminal.nxs"
    sed -i "s/Login\" >/Login\" >\n<option key=\"User\" value=\"$NX_LINUX_USER\" \/>/g" /tmp/.nx/config/terminal.nxs
    sed -i "s/\"Server host\" value=\".*\"/\"Server host\" value=\"$NX_SERVER\"/g" /tmp/.nx/config/terminal.nxs
    [ -z $NX_PORT ] || sed -i "s/\"Server port\" value=\".*\"/\"Server port\" value=\"$NX_PORT\"/g" /tmp/.nx/config/terminal.nxs
    [ -z $NX_DESKTOP ] || sed -i "s/\"Desktop\" value=\".*\"/\"Desktop\" value=\"$NX_DESKTOP\"/g" /tmp/.nx/config/terminal.nxs
    [ -z $NX_LINK_SPEED ] || sed -i "s/\"Link speed\" value=\".*\"/\"Link speed\" value=\"$NX_LINK_SPEED\"/g" /tmp/.nx/config/terminal.nxs
    [ -z $NX_CACHE_SIZE ] || sed -i "s/\"Cache size\" value=\".*\"/\"Cache size\" value=\"$NX_CACHE_SIZE\"/g" /tmp/.nx/config/terminal.nxs
fi

# set the background
xsetroot -solid "#666699"

# configure/start minimal window manager
cat >> ~/.ratpoisonrc << EOF
escape C-M-S-F12
startup_message off
EOF
ratpoison &

# start nxclient with predefined session, sleep until it runs
while :; do
    [ -z $NX_ADMIN ] && nxclient --session $NX_SESSION || nxclient
    while ps -C nxssh >/dev/null; do sleep 1; done
done
