#!/usr/bin/expect -f

# 0 - no error
# 2 - invalid userID/password combination
# 3 - source file not found on server

# argv 0 remote hostname
# argv 1 dir + filename 
# argv 2 userid 
# argv 3 passwd 
# argv 4 location on HMC

set timeout 1500

#set prompt "(%|#|\\\$) $"
#catch {set prompt $env(EXPECT_PROMPT)}
set USER [lindex $argv 2]
set SYSTEM [lindex $argv 0]
set PASSWORD [lindex $argv 3]
set KEYFILE [lindex $argv 1]
set LOC [lindex $argv 4]

system "export LANG=en_US"
set REMOTEHOST \[$SYSTEM\]
spawn /usr/bin/sftp -o StrictHostKeyChecking=no $USER@$REMOTEHOST
expect "assword:"
send "$PASSWORD\r"
# Check for wrong userid/pw
expect {
    -re "sftp>" { }
    -re "assword:" {
#	system "echo wrong password or user id"
	exit 2
    } 
}
send "lcd $LOC \r"
expect "sftp>"
send "get $KEYFILE \r"
expect {
   -re "Fetch" {
       system "echo see fetch and keyfile"
       exp_continue
   }
   -re "sftp> get" {
      exp_continue
   }
   -re "ouldn" {
       system "echo  see could"
       send "bye \r"
       exit 3
   }
   -re "Cannot" {
#       system "echo  see cannot"
       send "bye \r"
       exit 3
   }
   -re "sftp>" {
      send "bye \r"
      exit 0
   }
}
  expect "sftp>"
  send "bye \r"
exit 0
      
