#!/usr/local/bin/expect
#

#  Copyright (c) 1995 by Yatish Patel (pately@vivanet.com)
#  All Rights Reserved.
#
# tkTelnet is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# tkTelnet is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with tkTelnet; see the file COPYING.
# If not, write to the Free Software Foundation,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

set thespawn 0
proc get_info {userhome} {
    global hostname loginname passwd logtype
    set f [open "$userhome/.tkTeldat" r]
    gets $f info
    set hostname [lindex $info 1]
    set loginname [lindex $info 2]
    set passwd [lindex $info 3]
    set logtype [lindex $info 4]
    close $f
    set f [open "$userhome/.tkTeldat" w]
    puts $f "tkTelnet program data file"
    puts $f "Do not touch!"
    close $f
}

proc telnet_normal {hostname loginname passwd userhome} {
	global thespawn
    spawn -noecho telnet
    set thespawn $spawn_id
    set notloggedin 1
	set timeout 30
    while {$notloggedin==1} {
	expect {
		"telnet>" {send "open $hostname\n"}    
		"login:" {send "$loginname\n"}
		"Password:" {
			send "$passwd\n"
			set notloggedin 0
		}
	    "Unknown host" {
		set f [open "$userhome/.tkTelerror" w]
		puts $f "Unknown Host"
                close $f
		exit

	    } timeout {
		set f [open "$userhome/.tkTelerror" w]
		puts $f "Connection Timed Out"
                close $f
		exit
	    }
	}
    }
}

proc telnet_sra {hostname loginname passwd userhome} {
	global thespawn
spawn -noecho telnet $hostname
	set thespawn $spawn_id
set notloggedin 1
set timeout 20
while {$notloggedin==1} {
	expect {
           "User" {
		sleep 1
		send "$loginname\n"
	} 
	"Password:" {
		sleep 1
		send "$passwd\n"
		set notloggedin 0
	}
	"*Unknown host" {
		set f [open "$userhome/.tkTelerror" w]
		puts $f "Unknown Host"
		close $f
		set notloggedin 0
	        exit
	} timeout {
		set f [open "$userhome/.tkTelerror" w]
		puts $f "Connection Timed Out"
		close $f
	        exit
	}
	}
}
}
set userhome $env(HOME)
get_info $userhome
if {[string compare $logtype "User"]==0} {
    telnet_sra $hostname $loginname $passwd $userhome
}
if {[string compare $logtype "login:"]==0} {
    telnet_normal $hostname $loginname $passwd $userhome
}
set spawn_id $thespawn
interact {-i spawn_id}

