#!/usr/bin/perl

open(TTY, '/dev/tty');
select(TTY);
$| = 1;
select(STDOUT);

($them, $port) = @ARGV;
$them = "daisy.learning.cs.cmu.edu" unless $them;
$port = 4201 unless $port;

do 'sys/socket.h' || die "Can't do sys/socket.h: $@";
do 'sys/ioctl.h' || die "Can't do sys/ioctl.h: $@";

$SIG{'INT'} = 'dokill';
sub dokill { kill 9,$child if $child; }

$sockaddr = 'S n a4 x8';
chop($hostname = `hostname`);

($name, $aliases, $proto) = getprotobyname('tcp');
($name, $aliases, $type, $len, $thisaddr) = gethostbyname($hostname);
($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);

$this = pack($sockaddr, &AF_INET, 0, $thisaddr);
$that = pack($sockaddr, &AF_INET, $port, $thataddr);

socket(SOCK, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
bind(SOCK, $this) || die "bind: $!";
connect(SOCK, $that) || die "connect: $!";

$name = "packet"; $password = "bounce";

print "Connected to $them port $port.\n";
do { print "Name:";
  chop($name = <>); } unless $name;
do { print "Password:";
  chop($password = <>); } unless $password;

$ttymask = &funnyfileno("TTY");
$sockmask = &funnyfileno("SOCK");

select(SOCK);
print "connect $user $pass";
print "OUTPUTPREFIX ** PREFIX";
print "OUTPUTSUFFIX ** SUFFIX";
print "look";

while (1) {
  $rin = '';
  vec($rin, $ttymask, 1) = 1;
  vec($rin, $sockmask, 1) = 1;
  $win = '';
  $ein = $rin;
  $timeout = 5;

  ($nfound,$timeleft) =
     select($rout=$rin, undef, $ein, $timeout);

# print "nfound $nfound timeleft $timeleft rout $rout wout $wout eout $eout\n";

  if ($nfound < 0) {
    die("select: $!");
  }

  if (vec($eout,$ttymask,1)) {
    print "Exception on tty.\n";
#    last;
  }
  if (vec($eout,$sockmask,1)) {
    print "Exception on socket.\n";
#    last;
  }
  if (vec($rout,$ttymask,1)) {
    $nchars = '';
    ioctl(TTY, $FIONREAD, $nchars) || die "Can't ioctl: $!";
    $n = unpack('L', $nchars);
print "Reading $n\n";
    $data = read(TTY, $data, $n);
    print "tty: $data";
    select(SOCK);
    print $data;
    $| = 1;
    select(STDOUT);
  }
  if (vec($rout,$sockmask,1)) {
    $data = '';
    select(SOCK);
    $| = 1;
    select(STDOUT);
    $nchars = '';
print "f $FIONREAD\n";
    ioctl(SOCK, $FIONREAD, $nchars) || die "Can't ioctl: $!";
    $n = unpack('L', $nchars);
print "Reading $n\n";
    $data = read(SOCK, $data, $n);
    print $data;
  }
}
print "Goodbye!\n";
exit;

# Subroutines

sub funnyfileno {
    local ($fh) = @_;
    local ($n) = fileno($fh);
    if ($n < 8) { $n += 24; }
    elsif ($n < 16) { $n += 8; }
    elsif ($n < 24) { $n -= 8; }
    else { $n -= 24; }
    $n;
}

sub fhbits {
    local(@fhlist) = split(' ',$_[0]);
    local($bits);
    for (@fhlist) {
     vec($bits,&funnyfileno($_),1) = 1;
    }
    $bits;
}
