#!/bin/bash
#
# nxdesktop_helper - Small helper for external rdesktop program as needed by NX 3.0.0 backend.
#
# Copyright (c) 2007 by Fabian Franz <freenx@fabian-franz.de>
#
# License: GPL, v2
#
# SVN: $Id $
#

[ -z "$COMMAND_RDESKTOP" ] && COMMAND_RDESKTOP="rdesktop"

# Workaround for NXClient 3.2.0, sending wrong keyboard layout
[ "$agent_keyboard" = "ch" ] && agent_keyboard="de-ch"

# URL Decode
url_decode()
{
	# Translate spaces first (they cause trouble)
	s=$(echo $1 | tr '+' ' ')
	s=$(echo ${s} | sed 's/%20/ /g')
	for charno in $(echo ${s} | grep -o '%[0-9A-Fa-f]\{2\}' | tr -d '%' | uniq)
	do
		#... and then replace them
		char=$(printf "\x${charno}") #this is the actual character
		sedstr="s/%${charno}/\\${char}/g" # the char will need to be escaped
		s=$(echo "${s}" | sed ${sedstr})
	done
	echo "${s}"
}

# Remove urlencoding
windows_app=$(url_decode "$windows_app")

# we need to do this twice as nxclient is doing this twice ... uh ...
agent_password=$(url_decode "$agent_password")
agent_password=$(url_decode "$agent_password")

# setup commandline
set -- -u "$agent_user" -k "$agent_keyboard" -d "$agent_domain" -f -s "$windows_app" $AGENT_EXTRA_OPTIONS_RDP "$agent_server"

if [ -n "$agent_password" ]
then
	echo $agent_password | $COMMAND_RDESKTOP -p - "$@"
else
	$COMMAND_RDESKTOP "$@"
fi
