#!/bin/bash

# Copyright (C) 2010 Embecosm Limited

# Contributor Jeremy Bennett <jeremy.bennett@embecosm.com>
# Contributor Joern Rennecke <joern.rennecke@embecosm.com>

# This file is a board description for testing OpenRISC with uClibc and
# Or1ksim running Linux.

# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option)
# any later version.

# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.

# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.          

# -----------------------------------------------------------------------------
# For telnet targets we need to define some functions.

# -----------------------------------------------------------------------------
# Custom proc to close a telnet session

# @param[in] connhost  The connected host being closed.
# -----------------------------------------------------------------------------
proc telnet_close {connhost} {
    global board_info

    verbose "telnet_close: connhost $connhost" 3

    # Close the session
    set spawn_id [board_info $connhost fileid]
    catch close -i $spawn_id
    catch wait -i $spawn_id

    # Check we really succeeded in closing
    if [board_info $connhost exists fileid] {
	verbose "telnet_close: deleting remaining fileid"
	unset board_info(${connhost},fileid)
    }
}


# -----------------------------------------------------------------------------
# Custom proc to check if we have had too many failures

# @param[in] boardname  The board being closed.
# -----------------------------------------------------------------------------
proc telnet_failure_check { connhost errmess } {
    global board_info

    # Get the maximum failure count
    set max_fc 10

    if [board_info $connhost exists max_failure_count] {
	set max_fc [board_info $connhost max_failure_count]
    }
    verbose "telnet_failure_check: Max failure count $max_fc"

    # Increment the current failure count
    set fc 1
    if [board_info $connhost exists failure_count] {
	verbose "telnet_failure_check: Incrementing failure count"
	set fc [expr [board_info $connhost failure_count] + 1]
    }
    set board_info($connhost,failure_count) $fc
    verbose "telnet_failure_check: current failure count is $fc"

    # Die if we are over the limit
    if {$fc >= $max_fc} {
	error "Too many failures: $errmess"
    }
}


# -----------------------------------------------------------------------------
# Custom proc to exec programs using telnet

# We seem to only pass in the first of the arguments supplied to the command.

# The timeout is a mess. It seems to always be 10, not the timeout needed to
# execute a regression test (typicall 300 seconds). Fixed by not making it
# global and using our own timeout data.

# It also seems that only the first argument is passed.

# @param[in] hostname  The board we are telnetting to
# @param[in] cmd        The command to run
# @param[in] args       Arguments to the command

# @return  A list of the return code (-1 on failure) and any error message.
# -----------------------------------------------------------------------------
proc telnet_exec {hostname cmd args} {
    global board_info
    global verbose

    # Get the connected host name, if it exists. This code matches
    # telnet_open.
    verbose "telnet_exec: original hostname is $hostname"

    if {[board_info $hostname exists name]} {
	set connhost [board_info $hostname name]
    } else {
	set connhost $hostname
    }
    verbose "telnet_exec: connhost is $connhost"

    if [board_info $connhost exists hostname] {
	set hostname [board_info $connhost hostname]
    }
    verbose "telnet_exec: hostname is $hostname"

    # Get the first argument, if any.
    if { [llength $args] > 0 } {
	set pargs [lindex $args 0];
    } else {
	set pargs ""
    }

    verbose "telnet_exec: executing on $connhost, command \"$cmd\", pargs \"$pargs\""

    # Just check if we have more args. Potentially a second arg is an input
    # file.
    if { [llength $args] > 1 } {
	set tinp [lindex $args 1]
	if {$tinp != {}} {
	    verbose "telnet_exec: long args: $args"
	}
    }

    # Set the shell prompt
    if [board_info $connhost exists shell_prompt] {
	set shell_prompt [board_info $connhost shell_prompt]
    } elseif ![info exists shell_prompt] {
	# if no prompt, then set it to something generic
	set shell_prompt "\[^\r\n\]*\[$#\] "
    }

    # Start a new telnet session if one doesn't already exist. If sucessful
    # the fileid field associated with $connhost will be set to the spawn_id
    # of the new telnet process.
    if ![board_info $connhost exists fileid] {
	verbose "telnet_exec: opening new telnet connection"
	if {[telnet_open $connhost] == -1} {
	    return [list -1 "telnet to $hostname failed for $cmd, couldn't begin telnet session"]
	}
    }

    # The spawn_id we'll use throughout
    set spawn_id [board_info $connhost fileid]
    verbose "telnet_exec: spawn_id is now $spawn_id"
    
    # Use a relatively short timeout for most operations. Only the command
    # itself uses a long timeout.
    set timeout 30

    #Hit enter to make sure you get a shell prompt
    send -i $spawn_id "\r"

    expect {
	# A prompt indicates the current session is alive
	-i $spawn_id -re "$shell_prompt" {
	    verbose "telnet_exec: got prompt at start"
	}
	-i $spawn_id default {
	    # Timeout or EOF. Die if we have had too many failures
	    telnet_failure_check $connhost "no prompt at telnet start"

	    # Try closing the connection and reopening.
	    telnet_close $connhost
	    if {[telnet_open $connhost] != -1} {
		set spawn_id [board_info $connhost fileid]
		verbose "telnet_exec: new telnet session, spawn_id: $spawn_id"
		send -i $spawn_id "\r"
		exp_continue
	    } else {
		return [list -1 "telnet to $hostname failed for $cmd, couldn't get a shell prompt"]
	    }
	}
    }

    # Send the command. We can't cope with any input, so only the first
    # argument (group) is sent.
    send -i $spawn_id -- "$cmd $pargs\r"

    # We really should get the command echoed back immediately. This is a good
    # way of slurping up unexpected prompts. We first swap out any characters
    # from the command and args that might cause us grief.
    regsub -all "\\+" "$cmd $pargs" "." cmdpargs
    verbose "telnet_exec: command match string is \"$cmdpargs\""
    
    expect {
	-i $spawn_id -re "$cmdpargs" {
	    verbose "telnet_exec: got command echoed back"
	}
	-i $spawn_id default {
	    verbose "telnet_exec: command not echoed: command expect_out(buffer): \"$expect_out(buffer)\""
	}
    }

    # Set the telnet command custom timeout to wait for the command to
    # complete executing.
    if [board_info $connhost exists telnet_exec_timeout] {
	set timeout [board_info $connhost telnet_exec_timeout]
	verbose "telnet_exec: command timeout set to $timeout"
    } else {
	# Appropriate default
	set timeout 300
	verbose "telnet_exec: command timeout set to default value $timeout"
    }

    expect {
	-i $spawn_id -re "$shell_prompt" {
	    verbose "telnet_exec: got prompt after command"
	}
	-i $spawn_id default {
	    # Give up on timeout or EOF
	    telnet_close $connhost
	    return [list -1 "telnet to $hostname for $cmd $pargs failed (timeout)"]
	}		
    }

    # Remove unnecessary strings from the output string
    verbose "telnet_exec: command expect_out(buffer): \"$expect_out(buffer)\""
    regsub -all $cmdpargs "$expect_out(buffer)" {} output
    regsub "$shell_prompt" $output {} output
    regsub -all "\[\r\n\]" $output {} output

    if {$output == ""} {
	set output "(no output)"
    } else {
	set output "\"$output\""
    }	

    verbose "telnet_exec: command output $output"

    # Check the return status. Use a short timeout for this and following
    # commands.
    set timeout 30
    send -i $spawn_id "echo \$?\r"

    # Once again, look for the "echo" reflected back as a way of slurping up
    # unexpected prompts. We don't worry about timeout here - we'll sort that
    # out later.
    expect {
	-i $spawn_id -re "echo \\$\\?" {
	    verbose "telnet_exec: got \"echo\" echoed back"
	}
	-i $spawn_id default {
	    verbose "telnet_exec: echo not echoed: command expect_out(buffer): \"$expect_out(buffer)\""
	}
    }

    # Look for the shell prompt. Don't worry about timeout for now. It only
    # really matters if we don't get a valid status, which we'll discover
    # below.
    expect {
	-i $spawn_id -re "$shell_prompt" {
	    verbose "telnet_exec: got status shell prompt"
	}
	-i $spawn_id default {
	    verbose "telnet_exec: no status shell prompt: command expect_out(buffer): \"$expect_out(buffer)\""
	}
    }
	    
    # Regsub the output to get the status number
    verbose "telnet_exec: status expect_out(buffer): \"$expect_out(buffer)\""
    regsub -all {echo \$\?} $expect_out(buffer) {} status
    regsub "$shell_prompt" $status {} status
    regsub -all "\[\r\n \]" $status {} status
    verbose "telnet_exec: status \"$status\""

    # This shouldn't be neccessary...
    if {[regexp {[0123456789]+} $status] != 1} {
	warning "status not a number (\"$status\"), setting to 1"
	verbose "telnet_exec: status (\"$status\"), expect_out(buffer): \"$expect_out(buffer)\""
	set status 1

	# Die if we have had too many failures like this.
	telnet_failure_check $connhost "bad status"
    }

    if {$status == 0} {
	return [list "0" "$output"]
    } else {
	return [list "1" "$output"]
    }
}


# -----------------------------------------------------------------------------
# For FTP we need to redefine some existing functions to add additional
# features.

# -----------------------------------------------------------------------------
# Upload REMOTEFILE from HOST as LOCALFILE by FTP

# This version swaps the argument order, which is what the regression test
# seems to expect.

# Also allows a custom timeout to be set.

# @param[in] host        The host we are connected to.
# @param[in] localfile   The local file to send
# @param[in] remotefile  Name of file at remote end.
# -----------------------------------------------------------------------------
proc ftp_upload {host localfile remotefile} {
    global board_info

    set prompt "ftp>"
    verbose "ftping $remotefile from $host to $localfile"

    # JPB to set custom timeout (not marked global, so we don't need to save
    # and restore)
    if [board_info $host exists ftp_upload_timeout] {
	set timeout [board_info $host ftp_upload_timeout]
	verbose "FTP upload timeout set to $timeout"
    } else {
	# Appropriate default
	set timeout 15
	verbose "FTP upload timeout set to default value $timeout"
    }

    set spawn_id [ftp_open $host]
    if {$spawn_id < 0} {
	return ""
    }
    set loop 1

    while {$loop} {
	send -i $spawn_id "get $remotefile $localfile\n"
	expect {
	    -i $spawn_id -re ".*Too many open files.*$prompt" {
		ftp_close $host
	    }
	    -i $spawn_id -re ".*No such file or directory.*$prompt" {
		set loop 0
		set remotefile ""
	    }
	    -i $spawn_id -re "(^|\[\r\n\])226.*$prompt" {set loop 0}
	    -i $spawn_id -re "(^|\[\r\n\])\[0-9\]\[0-9\]\[0-9\].*$prompt" {
		set loop 0
		set remotefile ""
	    }
	    -i $spawn_id default {
		ftp_close $host
	    }
	}
	if {$loop} {
	    set spawn_id [ftp_open $host]
	    if {$spawn_id < 0} {
		return ""
	    }
	}
    }
    return $localfile
}


# -----------------------------------------------------------------------------
# Download LOCALFILE to HOST as REMOTEFILE by FTP

# This version takes a user specified timeout, which we need for our slow
# simulated connection.

# @param[in] host        The host we are connected to.
# @param[in] localfile   The local file to send
# @param[in] remotefile  Name of file at remote end.
# -----------------------------------------------------------------------------
proc ftp_download {host localfile remotefile} {
    global board_info

    set prompt "ftp>"

    verbose "putting $localfile $remotefile"

    if [board_info $host exists hostname] {
	set remotehost [board_info $host hostname]
    } else {
	set remotehost $host
    }

    set spawn_id [ftp_open $host]
    if {$spawn_id < 0} {
	return ""
    }
    set loop 1

    # JPB to set custom timeout (not marked global, so we don't need to save
    # and restore)
    if [board_info $host exists ftp_download_timeout] {
	set timeout [board_info $host ftp_download_timeout]
	verbose "FTP download timeout set to $timeout"
    } else {
	# Appropriate default
	set timeout 15
	verbose "FTP download timeout set to default value $timeout"
    }

    while {$loop} {
	send -i $spawn_id "put $localfile $remotefile\n"
	expect {
	    -i $spawn_id -re ".*Too many open files.*$prompt" {
		ftp_close $host
	    }
	    -i $spawn_id -re ".*No such file or directory.*$prompt" {
		set loop 0
		set remotefile ""
	    }
	    -re "(^|\[\r\n\])150.*connection for (.*) \[(\]\[0-9.,\]+\\)\[\r\n\]" {
		set remotefile $expect_out(2,string)
		exp_continue
	    }
	    -i $spawn_id -re "(^|\[\r\n\])226.*$prompt" {
		set loop 0
	    }
	    -i $spawn_id -re "Timeout.*$prompt" {
		ftp_close $host
	    }
	    -i $spawn_id -re "(^|\[\r\n\])\[0-9\]\[0-9\]\[0-9\].*$prompt" {
		set loop 0
		set remotefile ""
	    }
	    -i $spawn_id default {
		ftp_close $host
	    }
	}
	if {$loop} {
	    set spawn_id [ftp_open $host]
	    if {$spawn_id < 0} {
		return ""
	    }
	}
    }
    return $remotefile
}


# This is a list of toolchains that are supported on this board.
set_board_info target_install {or1k-linux}

# No multilib options needed by default.
process_multilib_options ""

# Load the generic configuration for this board. This will define a basic set
# of routines needed by the tool to communicate with the board.
load_generic_config "unix"

# Set up remote target info. We select the IP address using an external
# program which knows about all available Linuxes.
# set linux_hostname [exec [file dirname $env(DEJAGNUSCRIPTS)]/get-ip.sh --rotate]
set linux_hostname $env(OR1K_IP)
set_board_info hostname $linux_hostname
send_user "OR1K target hostname is $linux_hostname\n"

set_board_info username root

# Use the installed compilers to ensure we get search paths that will find
# uClibc.
send_user "set_board_info compiler /opt/or1k/bin/or1k-linux-gcc\n"
global GCC_UNDER_TEST
set GCC_UNDER_TEST "/opt/or1k/bin/or1k-linux-gcc"
global GXX_UNDER_TEST
set GXX_UNDER_TEST "/opt/or1k/bin/or1k-linux-g++"
set_board_info compiler /opt/or1k/bin/or1k-linux-gcc
set_board_info c++compiler /opt/or1k/bin/or1k-linux-g++
set target_alias "or1k-linux-uclibc"

set_board_info connect telnet
set_board_info shell_prompt          "\[^\r\n\]*# "
set_board_info telnet_username       "root"
set_board_info telnet_password       ""
set_board_info telnet_exec_timeout   1200

set_board_info file_transfer         ftp
set_board_info ftp_username          root
set_board_info ftp_password          ""
set_board_info ftp_download_timeout  120
set_board_info ftp_upload_timeout    120

# Options for the simulator
# set cfg_file [lookfor_file ${srcdir} libgloss/or1k/sim.cfg]
#set_board_info sim,options "-a \"-f ${cfg_file}\""

# We only support uClibc on this target.  We assume that all multilib options
# have been specified before we get here.
#set_board_info compiler  "[find_gcc]"

# We need to define this flag to generate default .gcda files if we are using
# a stock compiler, without the profopt.exp changes. No problem with doubling
# up the argument in normal circumstances.
set_board_info cflags    "-fprofile-dir=."
set_board_info cxxflags  "-fprofile-dir=."

# No linker script needed.
set_board_info ldscript ""

# This simulator isn't slow.
set_board_info slow_simulator 0

# Can't pass arguments to programs on this target..
set_board_info noargs  1

# Used by a few gcc.c-torture testcases to delimit how large the stack can
# be.
set_board_info gcc,stack_size 65536

# GDB options

# We can't do input in GDB (yet! HA!). It *will* do output, hurrah.
set_board_info gdb,noinferiorio 1
# Or pass arguments.
set_board_info gdb,noargs  1
set_board_info noargs 1
# And there's no support for signals.
set_board_info gdb,nosignals  1
