#!/usr/bin/expect -f

# argv 0 remote hostname
# argv 1 dir + filename 
# argv 2 userid 
# argv 3 passwd 
# argv 4 operation

#system "echo argv [string length $argv]\n"
#system "echo  0 = [lindex $argv 0]\n"
#system "echo  1 = [lindex $argv 1]\n"
#system "echo  2 = [lindex $argv 2]\n"
#system "echo  3 = [lindex $argv 3]\n"
#system "echo  4 = [lindex $argv 4]\n"

set timeout 5
set mode [lindex $argv 4]

spawn  bash 

set prompt "(%|#|\\\$) $"
catch {set prompt $env(EXPECT_PROMPT)}

if {[string compare $mode "Restore"] == 0} {
  send -- "/usr/bin/ssh -o StrictHostKeyChecking=no [lindex $argv 2]@[lindex $argv 0] ls [lindex $argv 1] >/dev/null\r"
} else {
  send -- "/usr/bin/ssh -o StrictHostKeyChecking=no [lindex $argv 2]@[lindex $argv 0] touch [lindex $argv 1]\r"

}
while 1 {
 expect -re "yes/no" {
      send  "yes\r"
  } -re "assword:" {
      send  "[lindex $argv 3]\r"
      break
  }
}

expect {
  "assword:" { puts "invalid id/pw" ; exit 32 }
  exit 32
}

expect {
   "*No such file*" { puts "not found" ; exit 39 }
}
expect {
   "*does not exist*" { puts "not found" ; exit 39 }
}

expect eof {send -- "echo $?\r "} "#" {send -- "echo $?\r"} $prompt {send -- "echo $?\r"}
expect -re "\r\n(.*)\r\n"
exit 0
