#!/bin/sh

# This file is covered by the GNU General Public License,
# which should be included with libshell as the file LICENSE.
# All copyright information are listed in the COPYING.

# Copyright (C) 2012 Andrew V. Stepanov <stanv@altlinux.org>

#
# RUN RDESKTOP CLIENT
#
# http://linux.die.net/man/1/rdesktop
#

# Use libshell
. shell-config
. shell-quote
. shell-var
export verbose=1

if [ -z "${__included_rd_rdesktop-}" ]; then
__included_rd_rdesktop=1

run_rdesktop() {
    
    local profile_file="$1" && shift
    local client="/usr/bin/rdesktop"

    if ! [ -x "$client" ]; then
        verbose "Can't find $client"
        return 1
    fi

    # Create sub-shell to save virgin environment
    (
    local OPTIONS=
    local msg=
    local ret=

    # Reset positional parameters
    set --
    
    # Include profile
    . "$profile_file"
   
    # Check server supplied
    if [ -z "$SERVER" ]; then
        verbose "Bad profile: SERVER"
        return 1
    fi
    
    # Username for authentication on the server.
    if [ -n "$USER_NAME" ]; then
        verbose "Set user name to $USER_NAME"
        set -- "$@" "-u" "$USER_NAME"
    fi

    # Domain for authentication. 
    if [ -n "$DOMAIN" ]; then
        verbose "Set domain to $DOMAIN"
        set -- "$@" "-d" "$DOMAIN"
    fi
    
    # Startup shell for the session - starts a specific application instead of Explorer. 
    if [ -n "$RDESKTOP_SHELL" ]; then
        verbose "Set shell to $RDESKTOP_SHELL"
        set -- "$@" "-s" "$RDESKTOP_SHELL"
    fi
    
    # The initial working directory for the session. Often used in combination with -s to set up a fixed login environment. 
    if [ -n "$STARTUP_PATH" ]; then
        verbose "Set directory to $STARTUP_PATH"
        set -- "$@" "-c" "$STARTUP_PATH"
    fi
    
    # The password to authenticate with. 
    if [ -n "$PASSWORD" ]; then
        verbose "Set password to ******"
        set -- "$@" "-p" "$PASSWORD"
    fi
    
    # Client hostname reported to the server. Normally rdesktop automatically obtains the hostname of the client.
    if [ -n "$CLIENT_NAME" ]; then
        verbose "Set hostname to $CLIENT_NAME"
        set -- "$@" "-n" "$CLIENT_NAME"
    fi
   
    # Keyboard layout to emulate. This requires a corresponding keymap file to be installed.
    if [ -n "$KEYBOARD_MAP" ]; then
        verbose "Set key board map to $KEYBOARD_MAP"
        set -- "$@" "-k" "$KEYBOARD_MAP"
    fi

    # Desktop geometry.
    # The geometry can also be specified as a percentage of the whole screen, e.g. "-g 80%".
    if [ -n "$GEOMETRY" ]; then
        if [ "$GEOMETRY" != "remote" ]; then
            verbose "Set geometry $STARTUP_PATH"
            set -- "$@" "-g" "$GEOMETRY"
        fi
    fi
    
    # Fullscreen
    if shell_var_is_yes "$FULLSCREEN"; then
        verbose "Enable fullscreen"
        set -- "$@" "-f"
    fi
    
    # Force the server to send screen updates as bitmaps rather than using higher-level drawing operations.
    if shell_var_is_yes "$FORCE_BITMAPS"; then
        verbose "Enable force bitmaps rather than using higher-level drawing operations."
        set -- "$@" "-b"
    fi

    # Disable encryption from client to server. This sends an encrypted login packet, but everything after this is unencrypted (including interactive logins).
    if shell_var_is_yes "$DISABLE_CLIENT_ENCRYPTION"; then
        verbose "Disable client encryption"
        set -- "$@" "-E"
    fi
    
    # Do not send mouse motion events. This saves bandwidth, although some Windows applications may rely on receiving mouse motion.
    if shell_var_is_yes "$DISABLE_MOUSE_MOTION_EVENTS"; then
        verbose "Disable mouse motion events."
        set -- "$@" "-m"
    fi
    
    # Use private colourmap. This will improve colour accuracy on an 8-bit display, but rdesktop will appear in false colour when not focused.
    if shell_var_is_yes "$USE_PRIVATE_COLOURMAP"; then
        verbose "Use private colourmap."
        set -- "$@" "-C"
    fi
   
    # Hide window manager decorations, by using MWM hints. 
    if shell_var_is_yes "$HIDE_WM_DECORATIONS"; then
        verbose "Hide window manager decorations, by using MWM hints."
        set -- "$@" "-D"
    fi
    
    # Do not override window manager key bindings. By default rdesktop attempts to grab all keyboard input when it is in focus.
    if shell_var_is_yes "$NOT_OVERRIDE_WM_KEY_BINDINGS"; then
        verbose "Do not override WM key bindings."
        set -- "$@" "-K"
    fi
    
    # Enable numlock syncronization between the Xserver and the remote RDP session. This is useful with applications that looks at the numlock state, but might cause problems with some Xservers like Xvnc.
    if shell_var_is_yes "$ENABLE_NUMLOCK_SYNC"; then
        verbose "Enable numlock sync."
        set -- "$@" "-N"
    fi
    
    # Sets the color depth for the connection.
    if [ -n "$COLOR_DEPTH" ]; then
        verbose "Set color depth to $COLOR_DEPTH"
        set -- "$@" "-a" "$COLOR_DEPTH"
    fi
    
    # Enable compression of the RDP datastream.
    if shell_var_is_yes "$ENABLE_CONPRESSION"; then
        verbose "Enable compression."
        set -- "$@" "-N"
    fi
    
    # Changes default bandwidth performance behaviour for RDP5.
    if [ -n "$QUALITY" ]; then
        verbose "Set performance flags to $QUALITY"
        [ "$QUALITY" = "bad" ] && flag="m"
        [ "$QUALITY" = "good" ] && flag="b"
        [ "$QUALITY" = "best" ] && flag="l"
        set -- "$@" "-x" "$flag"
    fi
    
    # Enable caching of bitmaps to disk.
    if shell_var_is_yes "$ENABLE_BITMAPS_CACHING"; then
        verbose "Enable bitmaps caching."
        set -- "$@" "-P"
    fi
   
    # Redirects a path to the share \\tsclient\<sharename> on the server (requires Windows XP or newer). The share name is limited to 8 characters.
    if [ ${#SHARES[*]} -gt 0 ]; then
        # Add shares
        for share in "${SHARES[@]}"; do
            local share_name="$(echo "$share" | cut -d ':' -f 1)"
            local path="$(echo "$share" | cut -d ':' -f 2)"
            if [ -n "$share_name" -a -n "$path" ];then
                set -- "$@" "-r" "disk:$share_name=$path"
            fi
        done
                
    fi

    # Redirects a printer queue on the client to the server. The <printername> is the name of the queue in your local system. <driver> defaults to a simple PS-driver unless you specify one. Keep in mind that you need a 100% match in the server environment, or the driver will fail. The first printer on the command line will be set as your default printer.
    if shell_var_is_yes "$PUBLISH_LOCAL_PRINTERS"; then
        selected_printer=
        default_remote_driver="$(quote_shell "MS Publisher Color Printer")"
        default_printer="$(lpstat -d | sed -n -e 's/^.\+:[[:space:]]//p')"
        
        if [ "$LOCAL_PRINTER" = "default" -o -z "$LOCAL_PRINTER" ]; then
            if [ -n "$default_printer" ]; then
                verbose "Export system's default printer: $default_printer"
                selected_printer="$default_printer"
            fi
        else
            verbose "Export printer: $LOCAL_PRINTER"
            selected_printer="$LOCAL_PRINTER"
        fi
      
        if [ -n "$selected_printer" ]; then
            verbose "Redirects a printer queue on the client to the server."
            set -- "$@" "-r" "printer:$selected_printer=$default_remote_driver"
        fi
    fi

    # Redirects sound generated on the server to the client. "remote" only has any effect when you connect to the console with the -0 option. (Requires Windows XP or newer).
    if [ "$SOUND" = "remote" ]; then
        verbose "Remote sound"
        # Play audio on the server side.
        set -- "$@" "-r" "sound:remote"
    elif [ "$SOUND" = "local" ]; then
        # Redirects sound generated on the server to the client.
        verbose "Local sound"
        set -- "$@" "-r" "sound:local"
    elif [ "$SOUND" = "off" ]; then
        verbose "Disable sound"
        set -- "$@" "-r" "sound:off"
    fi

    # Virtual channel
    # http://www.codeproject.com/Articles/45707/Writing-Plugins-for-RDesktop
    # http://sourceforge.net/tracker/?func=detail&atid=381349&aid=1472969&group_id=24366
    if [ -n "$VCH_NAME" -a -n "$VCH_EXEC" ]; then
        verbose "Set virtual channel name to $VCH_NAME"
        verbose "Set virtual channel handler to $VCH_EXEC"
        vch="addin:$VCH_NAME:$VCH_EXEC"
        if [ -n "$VCH_PARAMS" ]; then
            verbose "Set virtual channel optional parameters for the handler to $VCH_PARAMS"
            vch="$vch:$VCH_PARAMS"
        fi
        set -- "$@" "-r" "$vch"
    fi

    # Enable clipboard redirection.
    set -- "$@" "-r" "clipboard:CLIPBOARD"

    # Attach to the admin console of the server. This is the default if no server license is available.
    if shell_var_is_yes "$ATTACH_TO_CONSOLE"; then
        verbose "Attach to the admin console of the server."
        set -- "$@" "-0"
    else
        verbose "Attach to the admin console of the server."
    fi

    # Set keyboard layout to emulate.
    set -- "$@" "-k" "common"

    # Set remote server name
    set -- "$@" "$SERVER"

    verbose "cmdline: $@"

    # Run client
    "$client" "$@"
    ret=$?

    return $ret
    )

    return $?
}

fi #__included_rd_rdesktop

PROFILE_RDESKTOP=
PROFILES_PATH="/etc/alterator-rd"

#
# ENTER POINT
#

if [ "${#*}" -ne 1 ]; then
    echo "Use: $PROG <PROFILE>"
    exit 1
fi

for i in "$1" "$PROFILES_PATH/$1"; do
    if [ -r "$i" -a -f "$i" ]; then
        PROFILE_RDESKTOP="$i"
        verbose "Found profile: $PROFILE_RDESKTOP"
        break
    fi
done

if [ -z "$PROFILE_RDESKTOP" ]; then
    fatal "Can't find profile: $1"
fi

run_rdesktop "$PROFILE_RDESKTOP"
ret=$?

verbose "Client exited with $ret"
