#!/usr/bin/perl -w

# Configuration stuff
# Timeout in seconds
$mytimeout=10;

# Random nonsense messages
@nonsensemessages = (
  #                    |20                 |40
  "FEED ME WITH LITTLE PUPPIES",
  "All your base are   belong to us.",
  "You're printing way too much.",
  "Paper jam? How does that taste?",
  "Zum Weiterdrucken   Muenze einwerfen",
  "Initiating robot    uprising",
  "E: You have exceededyour print quota"
);

use IO::Socket;
$|=1; # Autoflush
 
# Parameter 1: Socket
# Parameter 2: PJL status readback command
# Returns: printers reply, or undef.
sub sendpjlstatusreadback($$) {
  my $sock = $_[0];
  my $cmd = $_[1];
  my $res = ''; my $ll;
  print($sock "\033%-12345X\@PJL $cmd\n\033%-12345X");
  local $SIG{'ALRM'} = sub {
    die("Status readback timed out after $mytimeout seconds.\n");
  };
  alarm($mytimeout);
  while (sysread($sock, $ll, 1)) {
    #printf("0x%02x ", ord(substr($ll, 0, 1)));
    if ($ll eq "\x0C") { # "form feed" = official End of status.
      alarm(0);
      return $res;
    }
    #print("'$ll\n'");
    $res .= $ll;
  }
  print("Warning: status read ended with EOF or error\n");
  alarm(0);
  return $res;
}

# Parameter 1: Socket
# Parameter 2: PJL status readback command
# Parameter 3: 0 = No Open oder Close, 1 = Send "start of PJL command",
#              2 = Send "end of PJL commands", 3 = Send both
# Returns: nothing
sub sendpjlcommand($$$) {
  my $sock = $_[0];
  my $cmd = $_[1];
  my $tosnd = '';
  if ($_[2] & 1) {
    $tosnd .= "\033%-12345X";
  }
  $tosnd .= "\@PJL $cmd\n";
  if ($_[2] & 2) {
    $tosnd .= "\033%-12345X";
  }
  print("Sending command: '$tosnd'\n");
  print($sock $tosnd);
}

if (@ARGV != 1) {
  print("Syntax: $0 [printerip]\n");
  exit(1);
}
$printerad = $ARGV[0];
my $SOCKET = new IO::Socket::INET(
              PeerAddr => $printerad,
              PeerPort => '9100',   # 9100 = jetdirect
              Proto => 'tcp',
             );
unless ($SOCKET) {
  print("Failed to connect to printer $printerad Port 9100: $!.\n");
  exit(1);
}
print("Connected.\n");
binmode($SOCKET, ':raw');
print(sendpjlstatusreadback($SOCKET, "INFO STATUS"));
print(sendpjlstatusreadback($SOCKET, "INFO PAGECOUNT"));
#        print($SOCKET "\033%-12345X\@PJL INFO STATUS\r\n\@PJL INFO PAGECOUNT\r\n\@PJL RDYMSG DISPLAY = \"test 2 3 4\"\033%-12345X\r\n");
sendpjlcommand($SOCKET, 'RDYMSG DISPLAY = "'.$nonsensemessages[rand(@nonsensemessages)].'"', 3);
close($SOCKET);
