#!/usr/bin/expect
#
# Reboot a machine connected to a Servertech Sentry power strip
#
# Copyright 2008 Google Inc., Ryan Kubiak <rkubiak@google.com>
# Released under the GPL v2

set P "reboot-sentry"

if {[llength $argv] < 3} {
    puts stderr "Usage: $P <ts host> <ts port> <outlet>"
    exit 1
}

set user {admn}
set pass {admn}
set tshost [lindex $argv 0]
set tsport [lindex $argv 1]
set outlet [lindex $argv 2]
set connected {0}
set attempts {0}

while {$connected == 0 && $attempts < 10} {
    spawn telnet $tshost $tsport
    sleep 5
    send "\r"
    set timeout 10
    set attempts [ expr $attempts +1 ]
    expect {
        #Connection closed
        "Connection closed by foreign host." {
            puts "Retrying attempt $attempts"
            set rand [expr round(rand() * 15 + 6)]
            puts "Waiting $rand before next attempt"
            sleep $rand
          }
        #Already logged in
        "Switched CDU:" {
            set connected {1}
            send "reboot $outlet\r"
            expect "Command successful"
            send "logout\r"
            puts "Machine successfully rebooted."
            exit 0
              }
        #Login
        "Username" {
            set connected {1}
            send "$user\r"
            expect "Password:"
            send "$pass\r"
            expect "Switched CD:"
            send "reboot $outlet\r"
            expect "Command successful"
            send "logout\r"
            puts "Machine successfully rebooted."
            exit 0
            }
        timeout {
            puts "Timed out connecting."
            }
        }
    }

puts "Unable to connect after 10 connection attempts."
exit 1
