#!/usr/bin/perl -w -T
#
# signal-guest (linux)
# this runs on the host os
#
# version 0.1

$client = "172.21.3.2";
$port = 10242;

use Sys::Syslog;
use IO::Socket;
use Carp;


openlog('signal-guest', 'pid,ndelay,cons', 'daemon');


# timeout at 1 for speed.
# we'd use udp, except that I want the 3way handshake
if (! ($s = IO::Socket::INET->new(Proto=>'tcp', PeerPort=>$port,
                              PeerAddr=>$client, Timeout=>1) )) {
      syslog('info', "Unable to connect to tcp/$client:$port. %m");
      exit(0);
}

sub stripeol($) {
  my $cmd = $_[0];
  chop $cmd if (substr($cmd, -1, 1) eq "\012");
  chop $cmd if (substr($cmd, -1, 1) eq "\015");
  return $cmd;
}

$s->autoflush(1);
$l = stripeol(<$s>);
unless($l =~ /^\+/) {
  my $rm = substr($l, 1);
  my $m = 'Remote NAKed us!%s';
  if ($rm !~ /^[\w\s[:print:]]*$/) {
    $rm = '[unprintable string - remote message suppressed]';
  }
  $rm = " (Remote said: $rm)" unless ($rm eq '');
  syslog('err', $m, $rm);
  close $s;
  exit(1);
}
print $s "s\015\012";
$l = stripeol(<$s>);
unless($l =~ /^\+/) {
  my $rm = substr($l, 1);
  my $m = 'Remote would not sleep%s';
  if ($rm !~ /^[\w\s[:print:]]*$/) {
    $rm = '[unprintable string - remote message suppressed]';
  }
  $rm = " Remote said: $rm" unless ($rm eq '');
  syslog('err', $m, $rm);
  print $s "q\015\012";
  close $s;
  exit(1);
}
syslog('info', "remote will sleep");
close $s;

closelog();

