#!/usr/bin/expect

proc critical { mesg } {
	puts "CRITICAL: $mesg"
	exit 2
}

proc unknown { mesg } {
	puts "UNKNOWN: $mesg"
	exit 3
}

if { $argc < 4 } {
	unknown "Usage: $argv0 <host> <netid> <passwd> <timeout>"
}

set host [lindex $argv 0]
set netid [lindex $argv 1]
set pwd [lindex $argv 2]
set timeout [lindex $argv 3]

log_user 0
set stty_init "-echo"
spawn -noecho openssl s_client -crlf -quiet -connect $host:993

expect "OK*\r\n" { } \
	"connect:err" { critical "Unable to establish connection with IMAP server" } \
	timeout { critical "No response while connecting to server" }

# puts $expect_out(buffer)

send "a1 login $netid $pwd\r"
expect "a1*OK*\r\n" { } \
	"*NO*\r\n" { critical "Login failed" } \
	"BAD" { unknown "Script error on login" } \
	timeout { critical "No response from server when logging in" }

# puts $expect_out(buffer)

send "a2 select inbox\r"
expect "a2*OK*\r\n" { } \
	"*NO*\r\n" { critical "Unable to select INBOX" } \
	"BAD" { unknown "Script error on inbox select" } \
	timeout { critical "No response from server when selecting inbox" }

# puts $expect_out(buffer)

send "a3 logout\r"
expect "a3*\r\n"
# puts $expect_out(buffer)

close

puts "OK: IMAP login successful"
exit 0

