#  $Id: procs.exp,v 1.79 2001/01/10 15:01:47 bryony Exp $
#  Copyright (C) 1999-2000 The Santa Cruz Operation
#  This software code contains proprietary information
#  and should be treated as confidential.

##############################################################################
# This proc decides how to launch the app then
# splits the amount to send to 200 chars per line
global env
proc execute {cmd} {
    while {[string length $cmd] > 200} {
	send -s "[string range $cmd 0 199]"
	send -s "\\\r"
	set cmd [string range $cmd 200 end]
    }
    send -s $cmd
}
###############################################################################
proc wait_for_prompt {} {
    global prompts match errorStrings
    set timeout 3

    if { $prompts(prompt) != ""  && $match != 0} {
	expect {
	    -re $prompts(prompt) {
	    }
	    timeout {
		# try to synchronise and guess the prompt
		send -s "echo -SYNC-\r"
		expect -re "echo -SYNC-.+-SYNC-..\(.*\)"
		set prompts(prompt) $expect_out(1,string)
		send_log "$errorStrings(reset_prompt) $prompts(prompt)\n"	
		set match 0
	    }
	}
    }

    if { $match == 0 } {
	expect {
	    -exact $prompts(prompt) {
	    }
	    timeout {
		# try to synchronise and guess the prompt
		send -s "echo -SYNC-\r"
		expect -re "echo -SYNC-.+-SYNC-..\(.*\)"
		set prompts(prompt) $expect_out(1,string)
		send_log "$errorStrings(reset_prompt) $prompts(prompt)\n"
	    }
	}
    }
}
###############################################################################
proc authenticate {type} {
    global env args exitCode timers messages
    # Check request for new authentication is allowed
    if { $env(TTA_AllowThirdTierDialog) == "none" } {
	# No dialog boxes allowed exit with an error
	send_error "Authentication credentials have failed"
	exit $exitCode(ErrApplicationServerLoginIncorrect)
   } else {
        # Dialog boxes allowed
        authrequest $type
        set args(username) $username
        set args(password) $password
        set args(newpassword) $newpassword
        # Restart the client timer
        clienttimer $timers(login) $messages(login) $timers(total)
    }
}
###############################################################################
proc initialise {} {
    global env timers
    progress "Initialising ..."
    #setbuffer -buffer 1
    # Start logging; uncomment this to send output to $env(TTA_LOGFILE)
    log_file $env(TTA_LOGFILE)
    # Override script variables with anything the user specified
    if { [info exists env(TTA_TerminalType) ] } {
	if { "$env(TTA_TerminalType)" != "" } {
	    set termtype "$env(TTA_TerminalType)\r"
	}
    }
}
###############################################################################
proc login {} {
    # This loop handles the login stage for telnet, rlogin and ssh
    global env prompts args patterns responses ssh exitCode errors \
           exp_beforelist timers match messages timeouts errorStrings

    if {[string compare $args(username) ""] == 0} {
	authenticate "-normal"
    }

    set timeout $timeouts(prelogin)
    clienttimer $timers(login) $messages(login) $timers(total)
    # Add loginincorrect to the expect before list to ensure we
    # always trap it - calls loginincorrect
    lappend exp_beforelist $patterns(loginincorrectpat)
    expect_before -brace [join $exp_beforelist]
    while (1) {
	expect {
            -re $errors(loginfail) {
                exit $exitCode(ErrApplicationServerLoginFailed)
            } -re $errors(loginnolicense) {
                exit $exitCode(ErrApplicationServerNoLicenseAvailable)
            } -re $errors(logindenied) {
                exit $exitCode(ErrApplicationServerLoginIncorrect)
            } $ssh(sshinsecurewarn) {
                exit $exitCode(ErrApplicationServerNoSecureConnection)
	    } timeout {
		# Failed to match any prompts
		set match 0
		expect *
		send_log "$errorStrings(login_timeout) \"$expect_out(buffer)\"\n"
		break
	    } -re $errors(loginfail) {
		exit $exitCode(ErrApplicationServerLoginFailed)
	    } -re $errors(loginnolicense) {
		exit $exitCode(ErrApplicationServerNoLicenseAvailable)
	    } -re $errors(loginsudenied) {
		# Reset all the script stuff and try to telnet
		# remove from expect_before the script which
		# does nothing if we get loginprompt again
		set x [lsearch $exp_beforelist $patterns(loginpat)]
		if {$x >= 0} {
		    set exp_beforelist [lreplace $exp_beforelist $x $x ]
		    expect_before -brace [join $exp_beforelist]
		}
		# remove from expect_before the script which
		# does nothing if we get pwprompt again
		set x [lsearch $exp_beforelist $patterns(pwpat)]
		if {$x >= 0} {
		    set exp_beforelist [lreplace $exp_beforelist $x $x ]
		    expect_before -brace [join $exp_beforelist]
		}
		locallaunch -abort
	    } $ssh(sshinsecurewarn) {
		set ssh(sshsecure) 0
		exit $exitCode(ErrApplicationServerNoSecureConnection)
	    } -re $errors(pwexpired) {
		passwordaged
		exp_continue
	    } -re $prompts(loginprompt) {
		# Delay sending the username to ensure it is accepted
                sleep .1
		send -s "$args(username)\r"
		# append to expect_before a script which
                # does nothing if we get loginprompt again
		set a [expect_before -info]
		lappend exp_beforelist $patterns(loginpat)
		expect_before -brace [join $exp_beforelist]
		exp_continue
 	    } -re $prompts(pwprompt) {
		# Delay sending the password to ensure that it is not echoed back
		sleep .1
		send -s -- "$args(password)\r"
		# append to expect_before a script which
                # does nothing if we get pwprompt again
		#set a "\r"
		#lappend exp_beforelist $patterns(pwpat)
		#expect_before -brace [join $exp_beforelist]
		# Check whether we have the login prompt in the exp_beforelist
		# if not insert it
		set x [lsearch $exp_beforelist $patterns(loginpat)]
		if {$x < 0} {
		    lappend exp_beforelist $patterns(loginpat)
		    expect_before -brace [join $exp_beforelist]
		}
		exp_continue
	    } -re $prompts(escapeprompt) {
		send $responses(escape)
		exp_continue
	    } -re $prompts(desktoprompt) {
		send -s $responses(desktop)
		exp_continue
	    } -re $prompts(termprompt) {
		send -s $responses(termtype)
		exp_continue
	    } -re $prompts(consoleprompt) {
		send -s $responses(console)
		exp_continue
	    } $ssh(sshcontinue) {
		send -s $ssh(sshyes)
		exp_continue
	    } -re $ssh(sshprompt) {
		send -s "$args(password)\r"
		exp_continue
	    } -re $prompts(prompt) {
		break
	    }
	}
    }
}
###############################################################################
proc startshells {} {
    global prompts match timeouts exp_beforelist errors exitCode \
    errorStrings

    # Logged in now so remove the loginincorrect string from the expect_before
    set x [lsearch $exp_beforelist $errors(loginincorrect)]
    if {$x >= 0} {
	set exp_beforelist [lreplace $exp_beforelist $x $x ]
	expect_before -brace [join $exp_beforelist]
    }
    # Now we have logged in set the buffer to read 1000 bytes
    setbuffer -buffer 1000
    # We seem to be logged in and accepting commands
    # Attempt to start a job control shell (ksh); if one doesn't
    # exist bourne shell suffices but may cause problems for apps
    # that dont handle SIGHUP well

    if { $match == 0 } {
	# If failed to match anything try to guess the prompt
	set timeout $timeouts(prelogin)
	send -s "echo -SYNC-\n"
	expect {
	    -re "echo -SYNC-.+-SYNC-..\(.*\)" {
		send_log "$errorStrings(reset_prompt) $prompts(prompt)\n"
		set prompts(prompt) $expect_out(1,string)
		if {$expect_out(1,string) == "" } {set prompts(prompt) "\#"}
		# reset the timeout so don't wait too long if the prompt changes
		set timeout $timeouts(loggedin)
	    } timeout {
		# No string available to guess prompt from so exit the launch
		send_log "$errorStrings(timed_out_login_failed)"
		exit $exitCode(ErrApplicationServerLoginFailed) 
	    }
	}
    }

    send -s "exec /bin/sh\n"
    wait_for_prompt
    send -s "\[ -f /bin/ksh \] && exec /bin/ksh\n"
    wait_for_prompt
    # Disable line editing mode for ksh
    send -s "set +o emacs ; set +o gmacs ; set +o vi\n"
    wait_for_prompt
}
###############################################################################
proc setupenv {} {
    global env prompts timers messages ssh
    # Export Environment Variables
    clienttimer $timers(env) $messages(env) $timers(total)
    set vars [split $env(TTA_ENVIRONMENT) ";" ]
    foreach i $vars {
	set idx [string first "=" $i]
	set name [string range $i 0 [expr $idx - 1] ]
	if {$env(TTA_CONNECTIONSERVICE) == "ssh" && $name == "DISPLAY" &&\
                $ssh(sshsecure) == 1 &&\
	        [string tolower $env(TTA_SECOND_TIER_DNSNAME)] != [string tolower $env(TTA_THIRD_TIER_DNSNAME)] } {
	      send -s "DISPLAY=$env(TTA_IPADDRESS):`expr \$DISPLAY : '.*:\\(.*\\)'` export DISPLAY\n"
	} else {
	    set a [string length $i]
	    if { $a > 0 } {
	      send -s "$i; export $name\n"
	      wait_for_prompt
           }
	}
    }
}
###############################################################################
proc mansetupenv {} {
    global env prompts

    # Create a var to hold the users third tier uid...
    execute "TTA_UID=\"`LANG=C LC_ALL=C id | sed 's/.*uid=\\(\[0-9\]\[0-9\]*\\).*/\\1/'`\"; export TTA_UID\n"
    wait_for_prompt

    # We want to remove any token files that are older than 24 hours... REMEMBER the files are in a temp dir...
    execute "find \${TMPDIR:-/tmp}/* -name \"TTA_SESSION_TOKEN.\$TTA_UID.*\" -a ! -mtime 0 -exec rm -f {} \";\" -o -type d -prune 2>/dev/null \n"
    wait_for_prompt

    # Export the list of third tier vars to the shell
    set vars [split $env(TTA_THIRD_TIER_VARS) ";" ]
    foreach i $vars {
        set idx [string first "=" $i]
        set length [string length $i]
        set name [string range $i 0 [expr $idx - 1] ]
        set value [string range $i [expr $idx + 1] $length]
        
        # Must quote the variable value
        regsub -all {'} $value {'"'"'} value
        
        # Check to see if the environment variable is the session token...
        if { [string first TTA_SESSION $name] == 0 } {

            # We only want to produce a TTA_SESSION_TOKEN file if the command is using
            # the tarantella command. This doesn't include everything that runs from
            # the tarantella/bin  directory...
            if { [string first bin/tarantella $env(TTA_COMMAND)] != -1 } {
                # Create a token file name...
                execute "$name=\"\${TMPDIR:-/tmp}/$name.\$TTA_UID.\$\$\"; export $name\n"
                wait_for_prompt

                # Write the token to the file...
                execute "( umask 177; echo '$value' > \"\$$name\" )\n"
                wait_for_prompt
            }
        } else {
            execute "$name='$value'; export $name\n"
            wait_for_prompt
       }
    }

    # If third-tier printing is installed on this machine then source the
    # config file.
    send -s "if \[ -f /etc/ttaprinter.conf \]; then . /etc/ttaprinter.conf; export LPDEST; fi\n"
    wait_for_prompt
}
###############################################################################
proc runauxcommands {} {
    global env prompts timers messages
    # Run Auxiliary Commands (e.g.X window manager)
    clienttimer $timers(runmain) $messages(runmain) $timers(total)
    if { [info exists env(TTA_AUXCOMMANDS) ] } {
       set apps [split $env(TTA_AUXCOMMANDS) ";" ]
       foreach i $apps {
	   set tosend "exec $i > /dev/null 2> $env(TTA_STDERR) &\n"
	   execute $tosend
	   wait_for_prompt
       }
    }
}
###############################################################################
# Execution of main command;
proc runmaincommand {} {
    global env exitCode output prompts
    dump_env
    # Record all the output in the buffer
    trace variable expect_out(buffer) w traceproc
    if {$env(TTA_WILLDISCONNECT) == 0} {
	# If we are not going to disconnect after launching
	# this is just a simple "exec"

	# Add in any command-line arguments
	if { [ info exists env(TTA_Arguments) ] } {
	    set tosend "exec $env(TTA_COMMAND) $env(TTA_Arguments)"
	} else {
	    set tosend "exec $env(TTA_COMMAND)"
	}
	# Execute the command 
	if [catch { execconnected $tosend }]  {
          # execconnected does not exist in 3.0.
          # Revert to 3.0 behaviour.
          execute $tosend
          expect $env(TTA_COMMAND)
          send -final "\n"
        }
 	scriptcomplete
   } else {
	# Otherwise we need to mess about somewhat ensuring that
	# applications don't get killed by SIGHUP or inappropriate i/o.
	# We also attempt to detect simple failures
	# due to lack of files etc.
	send -s "trap \"\" 1\n"
	wait_for_prompt
	expect *
	if { [ info exists env(TTA_Arguments) ] } {
	    execute "$env(TTA_COMMAND) $env(TTA_Arguments) < /dev/null > /dev/null 2>> $env(TTA_STDERR) || echo \"exec $env(TTA_COMMAND) exitcode\: \$? \"& killpid=\"\$killpid \$! \"\n"
	} else {
	    execute "$env(TTA_COMMAND) < /dev/null > /dev/null 2>> $env(TTA_STDERR) || echo \"exec $env(TTA_COMMAND) exitcode\: \$? \"& killpid=\"\$killpid \$! \"\n"
	}

        if { $env(TTA_CONNECTIONSERVICE) != "exec" && $env(TTA_CONNECTIONSERVICE) != "shell" } {
	    expect "\n"

        }

	set timeout 1
	expect {
	    timeout {
		send -s "\n"
		expect *
	    }
	}

	# Look for execution errors
	set errout {}
	set cmds {}
	set apps [split $env(TTA_AUXCOMMANDS) ";" ]
	lappend cmds $apps $env(TTA_COMMAND)
	foreach i $cmds {
	    set exp "$i exitcode: \[1-9\]\[0-9\]*"
	    if { [regexp -- $exp $output cmdres] } {
		lappend errout $cmdres
	    }
	}

	# Output any errors
	if { [llength $errout] != 0} {
	    # Write out the contents of the stderr file then remove it
	    send -s "cat $env(TTA_STDERR)\n"
	    wait_for_prompt
	    remove_stderr_file
	    sleep 1

	    send -s " Errors from application launch:\n"
	    foreach i $errout {
		send -s "$i\n"
	    }
	    send -s "exit\n"
	    exit $exitCode(ErrCommandExecutionFailed)
	}

	# Delete the stderr log file
	remove_stderr_file
	wait_for_prompt

	# Kill the subshells that are waiting for failure exit codes
	send -s "kill \$killpid 2>/dev/null\n"
	wait_for_prompt
	scriptcomplete
    }
}
###############################################################################
proc passwordaged {} {
    global prompts exp_beforelist patterns args env errors

    authenticate "-changed"
    # Manual login 0; Dialogue box 1
    if {$env(TTA_AGEDPASSWORD) == 0} {
	# remove from expect_before the script which
	# does nothing if we get loginprompt again
	set x [lsearch $exp_beforelist $patterns(loginpat)]
	if {$x >= 0} {
	    set exp_beforelist [lreplace $exp_beforelist $x $x ]
	    expect_before -brace [join $exp_beforelist]
	}
	# remove from expect_before the script which
	# does nothing if we get pwprompt again
	set x [lsearch $exp_beforelist $patterns(pwpat)]
	if {$x >= 0} {
	    set exp_beforelist [lreplace $exp_beforelist $x $x ]
	    expect_before -brace [join $exp_beforelist]
	}
    } else {
	expect_before
	expect {
	    -re $prompts(pwprompt) {
		send "$args(password)\r"
		expect {
		    -re $prompts(pwprompt) {
			send "$args(newpassword)\r"
			expect {
			    -re $prompts(pwprompt) {
				send "$args(newpassword)\r"
			    }
			}
		    }
		}
	    }
	}
    }
}
###############################################################################
proc buildcommand {} {
 global env cmd timers messages

    clienttimer $timers(build) $messages(build) $timers(total)
    switch $env(TTA_WindowsApplicationServer) {
	merge {
	    set cmd "win +x"

	    # Do we have any addition _merge_ command line arguments?
	    if { [info exists env(TTA_ProtocolArguments)] } {
		if { "$env(TTA_ProtocolArguments)" != "" } {
		    append cmd " $env(TTA_ProtocolArguments)"
		}
	    }

	    if { "$env(TTA_FilePath)" != "" } {
		if { "$env(TTA_FilePath)" != "-" } {
		    append cmd " +c $env(TTA_FilePath)"
		}
	    }
	}
	winframe {
	    set cmd "wfica"

	    # Do we have any addition _wfcmgr_ command line arguments?
	    if { [info exists env(TTA_ProtocolArguments)] } {
		if { "$env(TTA_ProtocolArguments)" != "" } {
		    append cmd " $env(TTA_ProtocolArguments)"
		}
	    }

	    if { "$env(TTA_FilePath)" != "" } {
		if { "$env(TTA_FilePath)" != "-" } {
		    append cmd " -desc $env(TTA_FilePath)"
		}
	    }
	}
    }
    set env(TTA_COMMAND) $cmd
}
################################################################################
proc auxwincommands {} {
    global prompts env timers messages

    clienttimer $timers(runmain) $messages(runmain) $timers(total)
    set auxcommands {}
    set apps [split $env(TTA_AUXCOMMANDS) ";" ]
    foreach i $apps {
	if { $env(TTA_WILLDISCONNECT) == 0 } {
	    send -s "$i &\n"
	} else {
	    set filename ""
	    if { [regexp -- "(\[^ \]*).*" $i foo filename] } {
		lappend auxcommands $filename
	    }
	    send -s "trap \"\" 1\n"
	    send -s "$i </dev/null >/dev/null 2> /dev/null || echo \"$filename exit code: \$?\" & killpid=\"\$killpid \$! \"\n"
	}
	wait_for_prompt
    }
}
###################################################################################
proc build3270command {} {
    global env prompts
    # Set up the 3270 variables

    set PortNumber ""
    set StyleFile ""
    set HostId ""
    set HostName ""
    set HostNameAndPortNumber ""
    set DisplayUI ""
    set FullCommand $env(TTA_COMMAND)

    if { [info exists env(TTA_IBMHostName) ] } {
	set HostName $env(TTA_IBMHostName)
	set HostNameAndPortNumber "$HostName"
    }
    if { [info exists env(TTA_PortNumber) ] } {
	set PortNumber $env(TTA_PortNumber)
    }
    if { [info exists env(TTA_StyleFile) ] } {
	set StyleFile $env(TTA_StyleFile)
    }
    if { [info exists env(TTA_HostId) ] } {
	set HostId $env(TTA_HostId)
    }
    # Note this will always be on for the X version
    # of the 3270 emulator as it is not possible to
    # disable the UI.
    if { [info exists env(TTA_DisplayUI) ] } {
	set DisplayUI $env(TTA_DisplayUI)
    }
    if { "$PortNumber" != "" } {
	set HostNameAndPortNumber "$HostNameAndPortNumber:$PortNumber"
    }
    if { "$HostName" != "" } {
	append FullCommand " -l $HostNameAndPortNumber "
    }
    if { "$StyleFile" != "" } {
	append FullCommand " -s $StyleFile "
    }
    if { "$HostId" != "" } {
	append FullCommand " -h $HostId "
    }
    if { "$DisplayUI" == "0" } {
	append FullCommand " -e "
    }
    set env(TTA_COMMAND) $FullCommand
}
###################################################################################
proc optimiselaunch {} {
    global env optimise args username
    # Optimisation of the launch
    # Offers the option to use /bin/su for launches on the second tier
    # If the third tier user is root, can connect using /bin/sh to avoid 
    # problems where telnet and su have been disabled.
    # The command locallaunch takes paramters of the type
    # locallaunch [-start | -abort] [ -user <bitmask> -root <bitmask> ]
    # where
    # -start : indicates start a locallaunch
    # -abort : abort the current local launch
    # -user  : configuration describing when to use /bin/su
    # -root  : configuration describing when to use /bin/su or /bin/sh
    # The bitmask provided is of the form  nosu | foreground | background 
    # where background indicates applications which are detached on launch 
    # whilst foreground represents applications which remain connected.
    # The nosu byte is ignored for users other than root.
    # Values of the bitmask give the following configuration:
    # 
    # value       -root                          -user
    #   0    all apps telnet               all apps telnet              
    #   1    back su, fore telnet	   back su, fore telnet 
    #   2    back telnet, fore su	   back telnet, fore su 
    #   3    all apps su          	   all apps su          
    #   4    all apps telnet               as for 0   
    #   5    back /bin/sh, fore telnet     as for 1   
    #   6    back telnet, fore /bin/sh     as for 2  
    #   7    all apps /bin/sh              as for 3
    #
    # For applications which use other transport methods such as rlogin
    # the above applies where telnet is replaced with rlogin.
    # If the arguments -user and -root are not provided the launches
    # default to the transport specified for the application.
    # The default configuration is -user 1 -root 3.

    if {[string compare $args(username) ""] == 0} {
	authenticate "-normal"
    }

    # For launches with the same 2nd and 3rd tier
    set vars [split $env(TTA_THIRD_TIER_VARS) ";" ]
    foreach i $vars {
	set idx [string first "=" $i]
	set length [string length $i]
	set name [string range $i 0 [expr $idx - 1] ]
	set value [string range $i [expr $idx + 1] $length]
	# Must quote the variable value
	regsub {'} $value {'"'"'} value
	set env($name) $value
    }

   if {[string compare $env(TTA_COMMAND) ""] != 0} {
       # Check whether the 2nd and 3rd tier are the same machine
       # Should ensure that the host is a dnsname otherwise we will drop out at this point
       if { [info exists env(TTA_SECOND_TIER_DNSNAME) ] && [info exists env(TTA_THIRD_TIER_DNSNAME) ] } {
	   if { [string tolower $env(TTA_SECOND_TIER_DNSNAME)] == [string tolower $env(TTA_THIRD_TIER_DNSNAME)] } {
	       # Samehost so attempt a local launch with the appended command
	       # Launch on the localhost with this command
	       locallaunch -start -user 1 -root 3 
	       # Pick up any new credentials
	       if { [string length $username] > 0} {
		   set args(username) $username
		   set args(password) $password
	       }
	   }
       }
   }
}

###################################################################################

proc build5250command {} {
    global env prompts

    set FullCommand $env(TTA_COMMAND)

    if { [info exists env(TTA_IBMHostName) ] } {
	set HostName $env(TTA_IBMHostName)
	if { "$HostName" != "" } {
            append FullCommand " -tnhost $HostName "

	    # Only set tnport if there is a hostname - teemX barfs if you set tnport but
	    # not tnhost (unless tn port is less than 10). Weird!

	    if { [info exists env(TTA_PortNumber) ] } {
		set PortNumber $env(TTA_PortNumber)
		if { "$PortNumber" != "" } {
		    append FullCommand " -tnport $PortNumber "
		}
	    }
	}
    }
    if { [info exists env(TTA_TNClose) ] } {
	set TNClose $env(TTA_TNClose)
	if { "$TNClose" != "" } {
            append FullCommand " -tnclose $TNClose "
	}
    }
    if { [info exists env(TTA_Maximise) ] } {
        set Maximise $env(TTA_Maximise)
        if { "$Maximise" == "1" } {
            append FullCommand " -ma "
        } else {
            append FullCommand " +ma "
        }
    }
    if { [info exists env(TTA_TopMenuBar) ] } {
	set TopMenuBar $env(TTA_TopMenuBar)
        if { "$TopMenuBar" == "0" } {
            append FullCommand " +mb "
        } else {
            append FullCommand " -mb "
        }
    }
    if { [info exists env(TTA_SettingsItem) ] } {
	set SettingsItem $env(TTA_SettingsItem)
        if { "$SettingsItem" == "0" } {
            append FullCommand " +si "
        } else {
            append FullCommand " -si "
        }
    }
    if { [info exists env(TTA_ForegroundColor) ] } {
	set ForegroundColor $env(TTA_ForegroundColor)
	if { "$ForegroundColor" != "" } {
#	    append FullCommand " -fg $ForegroundColor "
	    append FullCommand " -xrm \"*vt220*foreground: $ForegroundColor\" "
	}
    }
    if { [info exists env(TTA_BackgroundColor) ] } {
	set BackgroundColor $env(TTA_BackgroundColor)
	if { "$BackgroundColor" != "" } {
#	    append FullCommand " -bg $BackgroundColor "
	    append FullCommand " -xrm \"*vt220*background: $BackgroundColor\" "
	}
    }
    if { [info exists env(TTA_ButtonLevels) ] } {
	set ButtonLevels $env(TTA_ButtonLevels)
	if { "$ButtonLevels" != "" } {
            append FullCommand " -bl $ButtonLevels "
	}
    }
    if { [info exists env(TTA_KeyboardType) ] } {
        set KeyboardType $env(TTA_KeyboardType)
        if { "$KeyboardType" != "" } {
            append FullCommand " -kt $KeyboardType "
        }
    }

    set env(TTA_COMMAND) $FullCommand
}

######################################################################################
proc startdebug {} {
    global env debug_internal

    # Turn the internal debug on
    exp_internal -f $env(TTA_LOGFILE) 0
}
######################################################################################
proc loginincorrect {} {
    global exp_beforelist patterns errors

    # get new auth information
    authenticate "-normal"
    # remove from expect_before the script which
    # does nothing if we get loginprompt again
    set x [lsearch $exp_beforelist $patterns(loginpat)]
    if {$x >= 0} {
	set exp_beforelist [lreplace $exp_beforelist $x $x ]
	expect_before -brace [join $exp_beforelist]
    }
    exp_continue
}
######################################################################################
proc remove_stderr_file {} {
    #Delete the stderr log file from the third tier
    global env

#    send -s "\[ -f $env(TTA_STDERR) \] && rm -f $env(TTA_STDERR)\n"
}
######################################################################################
