#!/usr/bin/expect
#
# nxnode-login: spawns and controls ssh
#
# Copyright (c) 2004-2006 by Fabian Franz.
#
# License: GPL, version 2
#
# SVN: $Id: nxnode-login 512 2008-03-10 23:01:03Z fabianx $
#

# Syntax: nxnode-login {ssh|su|test-nx} user ssh-port executable command tosend

set auth_method [lindex $argv 0]
set user [lindex $argv 1]
set port [lindex $argv 2]
set executable [lindex $argv 3]
set command [lindex $argv 4]
set tosend [lindex $argv 5]
catch {set tosend $env(NXNODE_TOSEND)}
set command_ssh "ssh"
catch {set command_ssh $env(COMMAND_SSH)}
set host "127.0.0.1"
catch {set host $env(NODE_HOSTNAME)}

#
# Special test-nx instruction for nxsetup
#

if { "$auth_method"=="test-nx" } {
	set stty_init "raw icrnl -echo"

	set publickey ""
	catch {set publickey $env(NODE_PUBLICKEY)}
	
	set pid [spawn -noecho $command_ssh -2 -x -l "$user" "$host" -i "$publickey" -o "RhostsAuthentication no" -o "PasswordAuthentication no" -o "PubkeyAuthentication yes" -o "PreferredAuthentications publickey" -o "ConnectTimeout 3" -p "$port" "$executable $command" ]
	
	while {1} {
		expect {
			"Are you sure you want to continue connecting*" { send "yes\r" }
			"Permission denied*" { exit 1 }
			"HELLO NXSERVER - Version*\n" {
				break
			}
		}
	}
	expect "NX> 105" { send "quit\r" }
	expect "NX> 999 Bye"
	exit 0
}

#
# Log the user in via the supplied method.
#

expect_user -re "(.*)\n"
set password $expect_out(1,string)

set stty_init "raw icrnl -echo"

if { "$auth_method"=="ssh" } {
	set pid [spawn -noecho $command_ssh -2 -x -l "$user" "$host" -o "NumberOfPasswordPrompts 1" -p "$port" "$executable $command" ]
} elseif { "$auth_method"=="su" } {
        set env(LANG) "C"
	set pid [spawn -noecho su - "$user" -c "$executable $command" ]
} elseif { "$auth_method"=="guest" } {
	set pid [spawn -noecho $executable $command ]
} else {
	exit 1
}

while {1} {
	expect {
		"Are you sure you want to continue connecting*" { send "yes\r" }
		"assword*:"  { sleep 0.3; send "$password\r" }
		"SSH passphrase:"  { sleep 0.3; send "$password\r" }
		"Permission denied*" { exit 1 }
		"su: Authentication failure" { exit 1 }
		"NX> 1000 NXNODE - Version" {
			break
		}
	}
}

if { "$tosend"!="" } {
	send "$tosend\r"
}

expect {
	"NX> 716 finished" { }
	"NX> 700" {
			set timeout -1
			expect {
				"NX> 1001 Bye." { exit 0 }
				"NX> *" { exp_continue }
			}
			exit 0
		}
	"NX> 716 Public key is already present in:" { }
	"NX> 716 Public key added to:" { }
	"NX> 716 Terminating session * on user request." { }
	"NX> 716 Suspending session * on user request." { }
	"NX> 500 Error: " { exit 1}
}
expect "NX> 1001 Bye."
