#!/usr/bin/expect 
#
# reboot-rsa -- reboot systems with RSA management cards
#
# Reboot systems via their RSA (I) managment card interface.
# 
# usage: 
# reboot-rsa <userid> <password> <connect commands> ...
#
# example
# reboot-rsa FOO BAR telnet 1.2.3.4
#
# (C) Copyright IBM Corp. 2004, 2005, 2006
# Author: Dave Hansen <haveblue@us.ibm.com>
#
# The Console Multiplexor is released under the GNU Public License V2
#
set P "reboot-rsa"

if {[llength $argv] < 3} {
	puts stderr "Usage: $P <username> <password> <cmd> ..."
	exit 1
}
set username [lindex $argv 0]
set password [lindex $argv 1]

log_user 0
#stty echo
#log_file -a "$logfile"

proc note {m} {
	global P
	puts "$P: $m"
}
proc warn {m} {
	global P
	puts "$P: WARNING: $m"
}
proc winge {m} {
	global P
	puts "$P: ERROR: $m"
}

set elapsed_time 0
set timeout 10

set command [lrange $argv 2 end]
eval spawn [lrange $argv 2 end]

note "Logging into service processor with command \"$command\" to restart it";

expect {
	"Connection closed by foreign host." {
		winge "Telnet connection closed."
		exit 1;
	}
	"Unable to connect to remote host:" {
		winge "Someone may already have the service processor";
		exit 2;
	}
	"Login ID:" {
		send "$username\t$password\r"
	}
	timeout {
		winge "never saw opening screen with \"Login ID:\""
		exit 2;
	}
}

expect {
	"Log Off" {
		send "\t\t\t\t\r"
		note "Saw opening screen, selecting \"Server Power/Restart\"";
	}
	timeout {
	}
}

expect {
	"Restart Server Immediately" {
		note "Saw \"Server Power/Restart\" screen.  Selecting \"Restart\"";
		send "\t\t\t\t\t\r";
	}
}

expect {
	"Restarting the system immediately" {
		note "Saw restart confirmation prompt, pressing enter";
		send "\r"
	}
}

expect {
	"The system is performing a Restart Server Immediately" {
		note "the system is restarting";
		exit 0;
	}
}

winge "an error occurred while restarting the server"
exit 1;
