#!/usr/bin/perl

my $top;

if (@ARGV && $ARGV[0] eq '--top') {
  $top = 1;
  shift @ARGV;
}
die("Usage: bs_serverstatus [--top] <statusfile>\n") unless $ARGV[0];
$| = 1;
print "\033[H\033[J" if $top;
my $nl = "\n";
$nl = "\033[K\n" if $top;
while(1) {
  open(STA, '<', $ARGV[0]) || die("$ARGV[0]: $!\n");
  my $now = time();
  my $sta;
  my $empty = '';
  while ((sysread(STA, $sta, 256) || 0) == 256) {
    my ($ti, $pid, $state, $data) = unpack("NNNZ244", $sta);
    if ($state == 0) {
      $empty .= "-$nl";
      next;
    }
    my $d = $now - $ti;
    if ($state == 1) {
      $state = 'F';
    } elsif ($state == 2) {
      $state = 'R';
    } else {
      $state = '?';
    }
    printf "%s%s %3d %5d %s$nl", $empty, $state, $d, $pid, $data;
    $empty = '';
  }
  close STA;
  last unless $top;
  print "\033[J";
  sleep(1);
  print "\033[H";
}
