#!/usr/bin/perl -w

# based off of hphack.pl by gil cohen sung@lostgeeks.net
# based off of _HP Printer Hack_ by sili@l0pht.com
# written by Schuyler Erle <schuyler@iconocla.st>

use IO::Socket;
use Time::HiRes qw( sleep );
use constant WIDTH  => 16;
use constant DELAY  => 1/3;
use constant QUIET  => 3600;
use constant MSGLEN => 120;
use constant ITER   => 3;
use constant WATCH  => 1;
use strict;

BEGIN {$|++}

sub fortune {
    my $msg = qx{/usr/games/fortune -s -n @{[MSGLEN]}};
    $msg =~ s/\s+/ /gos;
    $msg;
}

sub send_msg {
    my ($host, $msg) = @_;
    my $sock = new IO::Socket::INET (
	PeerHost => $host, PeerPort => 9100, Proto => "tcp" );
    unless ( $sock ) {
	warn "\nCouldn't connect to $host: $!\n";
	return 1;
    }
    print STDERR "\r[$host] $msg", (" ") x (WIDTH - length $msg) if WATCH;
    print $sock qq{\033%-12345X\@PJL RDYMSG DISPLAY = "$msg"\n\033%-12345X\n};
    close($sock);
    return 1;
}

sub marquee {
    my ($host, $message) = @_;
    $message = (" " x WIDTH) . $message . (" " x (WIDTH - 1));
    for (my $i = 0; $i < length($message) - WIDTH; $i++) {
	my $m = substr($message, $i, WIDTH);
	send_msg($host => $m) or return 0;
	sleep DELAY;
    }
    return 1;
}

my @host = <STDIN>; chomp for @host;
die "Need a list of hosts!\n" unless @host;
while (1) {
    my $target = $host[int rand @host];
    my $msg    = fortune;
    print "<@{[scalar localtime]}> [$target] $msg\n";
    marquee( $target => $msg ) or last for (1 .. ITER);
    sleep 1 until send_msg( $target => "READY");
    print STDERR "\n" if WATCH;

    my $delay  = 1 + int rand QUIET;
    print "<@{[scalar localtime]}> sleeping $delay seconds...\n";
    sleep $delay;
}
