#!/bin/bash
#rd/c waTricky - brendan@swiftspirit.co.za
#v1.3.1
#2009-03-18
#License GPLv3
#installation covered at http://dogma.swiftspirit.co.za/archives/11

# You shouldn't ordinarily have to change anything below this line
set -e

#DEFAULTS
res="1024x768"
readonlyshare="/media/rd"
writableshare="/media/rd/honey"
defaultuser="Administrator"

[ -e ~/.rd ] && . ~/.rd

usageinfo="echo Usage: rd(c) [-s shell] server [username]"

function remote {

tmplog="/tmp/.rd.$RANDOM.log"

set +e
rdesktop -r disk:rd=$1 -r disk:rd=$2 -g $3 -a $4 -k $5 $6 -u $7 $8 $9 2> $tmplog.err > $tmplog 
set -e

remotehost=$8

cat $tmplog $tmplog.err | grep -i error
cat $tmplog $tmplog.err | grep -i error > /dev/null && echo -n Remote Desktop to $remotehost failed.
cat $tmplog $tmplog.err | grep "unable to resolve host" > /dev/null && echo " Could not resolve host name."
cat $tmplog $tmplog.err | grep "ERROR: recv: Connection reset by peer" > /dev/null && echo You may have been disconnected by another user on $remotehost.
cat $tmplog $tmplog.err | grep "ERROR: .*: Connection refused" > /dev/null && echo The server $remotehost refused the connection.
cat $tmplog $tmplog.err | grep -i error > /dev/null && echo -n Press [Enter] to continue.

# Comment these out for debugging purposes
rm -f $tmplog
rm -f $tmplog.err

} #function remote

mycmd=`echo $0 | sed -r 's/.+\/([^\/]*)$/\1/'`

if [ "$mycmd" == "rdc" ]
 then rdconsole="-0"
 else rdconsole=""
fi

set +e
rdesktop 2>&1 | grep "command not found" > /dev/null && echo "The rdesktop client was not found." && echo "Please install it from your distribution or see http://www.rdesktop.org/" && exit 8
set -e

case $1 in
 "-h") $usaginfo ;;
 "--help") $usageinfo ;;
 *) case $# in
     0) $usageinfo ;;
     1) case $1 in
         "-s") echo "Invalid syntax: -s without a shell argument" ; $usageinfo ;;
         "--shell") echo "Invalid syntax: --shell without a shell argument" ; $usageinfo ;;
         *) remote $readonlyshare $writableshare $res 16 en-us -z $defaultuser $1 $rdconsole & ;;
        esac ;;
     2) case $1 in
         "-s") echo "Invalid syntax: no server argument" ; $usageinfo ;;
         "--shell") echo "Invalid syntax: no server argument" ; $usageinfo ;;
         *) remote $readonlyshare $writableshare $res 16 en-us -z $2 $1 $rdconsole & ;;
        esac ;;
     3) case $1 in
         "-s") remote $readonlyshare $writableshare $res 16 en-us -z $defaultuser $3 -A -s $2 $rdconsole & ;;
         "--shell") remote $readonlyshare $writableshare $res 16 en-us -z $defaultuser $3 -A -s $2 $rdconsole & ;;
         *) echo -n "Invalid syntax: " ; $usageinfo ;;
        esac ;;
     4) case $1 in
         "-s") remote $readonlyshare $writableshare $res 16 en-us -z $4 $3 -A -s $2 $rdconsole & ;;
         "--shell") remote $readonlyshare $writableshare $res 16 en-us -z $4 $3 -A -s $2 $rdconsole & ;;
         *) echo -n "Invalid syntax: " ; $usageinfo
        esac ;;
    esac ;;
esac
