#!/usr/bin/perl
## $Id: wcatstat 2703 2008-08-27 20:27:34Z andre.dig $
## watchcatd - Watchcat Daemon
## See copyright notice in distro's COPYRIGHT file

use warnings;
use strict;
use Socket;

sub print_cat (\%)
{
    my ($cat) = @_;
    print($$ == $cat->{pid} ? '*' : '');
    print($cat->{fd}, ':', $cat->{status}, ':', $cat->{version}, ':',
    	  $cat->{timeout}, ':', $cat->{pid}, ':', $cat->{uid}, ':',
          $cat->{signal}, ':', $cat->{info}, "\n");
}

#
# Main code.
#

$< == 0 or die "Only the super user can execute this script\n";

socket(WCAT, PF_UNIX, SOCK_STREAM, 0);
connect(WCAT, sockaddr_un("/var/run/watchcat.socket")) or
    die "Can't connect to watchcatd: $!\n";

send(WCAT, "version: 1\ncommand: stat\n\n", 0) or die "Error: $!\n";

my %cat;
my $i = 0;
while(<WCAT>)
{
    my ($field_name, $field_value) = /^([^:]+):\s*([^\n]*)$/;

    if (not defined $field_name) {
        $_ eq "connect\n" and die "Too many connections\n";
        $_ eq "\n" or die "Invalid format, line: `$_'\n";
        last;
    }

    if ($field_name eq "block") {
        if ($i == 0) {
            print("\nfd:status:version:timeout:pid:uid:signal:info\n");
        }
        else {
            print_cat(%cat);
	    %cat = ();
        }
        $i++;
        next;
    }

    if ($i > 0) {
        $cat{$field_name} = $field_value;
        next;
    }

    print "${field_name}: $field_value\n";
}
close WCAT;

print_cat(%cat) if $i > 0;
print("\n");
