#!/usr/bin/expect --
################################################################################
#
# File: rssh -- ssh as root
#
# Description:	provides the same function as ssh, but this supplies the root
#				password when prompted.
#
# Notes:
#		The root password is set in ../lib/defaults
#         
#
#      -*- OpenSAF  -*-
#
# (C) Copyright 2008 The OpenSAF Foundation
#
# 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. This file and program are licensed
# under the GNU Lesser General Public License Version 2.1, February 1999.
# The complete license can be accessed from the following location:
# http://opensource.org/licenses/lgpl-license.php
# See the Copying file included with the OpenSAF distribution for full
# licensing terms.
#
# Author(s):
#           Hewlett-Packard Company
#
################################################################################

# Get the name of this script.
set MyName [lindex [split $argv0 {/}] end]
set caller "$MyName"

################################################################################
#                                 Subroutines
################################################################################

#*******************************************************************************
# SetLibraryPath: Sets the library path for common libraries
# Input: none
# Output: exits with value 0
#*******************************************************************************
proc SetLibraryPath {argv0} {
   global basepath locpath
   global env
   global VERBOSE

   if {![info exists VERBOSE]} {
      set VERBOSE 0
   }
   set libDir "tests/hisv/lib"
    # Get the path to the our libraries
    if {$VERBOSE} {
       send_user "\n\[SM] SetLibraryPath:\n"
       send_user "\targv0 = $argv0\n"
    }
    set failed [catch {exec which $argv0} pathToMe]
     # If the path to this tool is relative to this directory,
     #   substitute $PWD.
    regsub {^./[^/]+} $pathToMe $env(PWD) pathToMe
     # set locpath to this directory
    regsub {/[^/]+$} $pathToMe "" locpath

    if {$VERBOSE} {
       send_user "\tpathToMe = $pathToMe\n"
       send_user "\tlocpath  = $locpath\n"
       send_user "\tfailed  = $failed\n"
    }
    if [info exists env(BASEPATH)] {
        # Use the environment variable BASEPATH if set:
       set basepath "$env(BASEPATH)"
    } \
    else {
        if { ! $failed } {
           # "which $MyName" succeeded
           set pathDirs [split $locpath /]
           set pLen [expr [llength $pathDirs] - 1]

            # Work backwards through the path to try to
            #  find the path to the library directory
           for {set i $pLen} {$i > 0 } {incr i -1} {

               if {$i == $pLen} {
                  set dummyPath $pathToMe
               }
               regsub {/[^/]+$} $dummyPath "" dummyPath
               if {[file exists $dummyPath/libsm]} {
                  set basepath $dummyPath
                  break
               } \
               elseif {[file exists $dummyPath/lib/libsm]} {
                  set basepath $dummyPath/lib
                  break
               }
           }

           if {![info exists basepath]} {
               send_user "ERROR: Can't find common library directory $libDir\n"
               exit 2
           }
        } \
        else {
            puts "ERROR:  Can't figure out library directory location!"
            exit 1
        }
    }

    if {$VERBOSE} {send_user "\tFound library path $basepath\n"}
}

#*******************************************************************************
# Usage: Print usage message
# Input: none
# Output: exits with value 0
#*******************************************************************************
proc Usage {} {
   global MyName
   global domain
   global ilo_user ilo_passwd
   global user passwd

   puts "\nUsage: $MyName -sut=<ilo_hostname> \[optional]"
   puts "    Required options:"
   puts "\t-sut=<ilo_hostname>"
   puts "\t    hostname is the hostname of the system under test."
   puts ""
   puts "    Test-related options:"
   puts ""
   puts "    Other options:"
   puts "\t-ilo_passwd=<ilo_admin_passwd>"
   puts "\t    ilo_admin_passwd is the administrator password on the system under test."
   puts "\t    (default: $passwd)."
   puts "\t-ilo_user=<administrator>"
   puts "\t    user_name to log into iLO virtual serial console as"
   puts "\t    (default: $user)."
   puts ""
   puts "    Login-related options:"
   puts "\t-user=<root_user>"
   puts "\t    root_user is the login name for a user with root privileges."
   puts "\t    default: $user."
   puts "\t-password=<root_user_password>"
   puts "\t    The password for the user specified above."
   puts ""
   exit 0
} ;# End Usage


################################################################################
#                              End Subroutines
################################################################################
# Set verbose early to get verbose output from search for library
# path and command-line parsing
if {[regexp -- {-v} $argv]} { set VERBOSE 1 }

# Set library path
SetLibraryPath $argv0

#***************************** Global Variables ********************************
source $basepath/defaults

# Source libraries.
source "$basepath/libcmdline"
source "$basepath/stdlib"
source "$basepath/libilo"
source "$basepath/libsm"
source "$basepath/liblinux"
source "$basepath/libstate"

################################################################################
#                           Overloaded Subroutines
################################################################################
#  Add subroutines, e.g., Done, here to override the
#  default action as defined in the libraries above.

################################################################################
#                         End Overloaded Subroutines
################################################################################

# Set interrupt handlers
SetSigTraps


#************************** Configuration Loading ******************************

# Override default settings with command-line options
ParseCanonicalCmdline argv
if {[info exists argv] && [llength $argv]} { SshParseCmdLine argv }
if {![info exists prompt]} { set prompt $root_prompt }

# Show the user what's going on...
log_user 1

# Set the Expect log file if we are in verbose mode.
set log "$MyName"
set log [split $log {.}]
set logfilename "[lindex $log 0].log.[pid]"

if {[info exists env(DRYRUN)] && $env(DRYRUN)} {
   set DRYRUN 1
   set VERBOSE 3
}

#**************************** Start Debug-Logfile ******************************
if { $VERBOSE || [info exists env(DEBUG)] && $env(DEBUG)} {
    exp_internal -f $logfilename 0
    send_user "\n\[SM] Logfile is $logfilename\n"
}

#*************************** Connect to the System *****************************
set timeout $timeout_setting

if {$VERBOSE} {
   send_user "\[SM] $MyName:\n"
   if {[info exists host]} {send_user "\thost is $host\n"}
   if {[info exists cmd]} {send_user "\tcmd is $cmd\n"}
   if {[info exists user]} {send_user "\tuser is $user\n"}
   if {[info exists passwd]} {send_user "\tpasswd is $passwd\n"}
   if {[info exists domain]} {send_user "\tdomain is $domain\n"}
}
if { $DRYRUN } {
   if {[info exists argv] && [llength $argv]} {
      eval spawn [lrange $argv 0 end]
      set MainProc $spawn_id
   }
}

# Clean out any chassis codes
expect *

# Perform the connection
set timeout $timeout_setting
set connected [ConnectSsh $user $passwd $host cmd]
if [info exists cmd] {
   if {$cmd != "" && ![regexp {{}} $cmd]} {
      if {$connected} {
         ErrorMessage "Something's amiss -- connected to $host" 1
      }
   }
} \
elseif {!$connected} {
   ErrorMessage "Failed to connect to $host as $user" 1
}




#  OK, interact if no command to run
if {$connected} {
   interact
   set connected 0
}

Done 0
