fix rcmd <call> sh/fdx problem
[spider.git] / perl / watchdbg
1 #!/usr/bin/perl
2 #
3 # watch the end of the current debug file (like tail -f) applying
4 # any regexes supplied on the command line.
5 #
6 # examples:-
7
8 #   watchdbg g1tlh       # watch everything g1tlh does
9 #   watchdbg 2 PCPROT       # watch all PCPROT messages + up to 2 lines before
10 #   watchdbg gb7baa gb7djk   # watch the conversation between BAA and DJK 
11 #
12
13 require 5.004;
14
15 # search local then perl directories
16 BEGIN {
17         # root of directory tree for this system
18         $root = "/spider"; 
19         $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
20         
21         unshift @INC, "$root/perl";     # this IS the right way round!
22         unshift @INC, "$root/local";
23         sub main::mkver {}
24 }
25
26 use IO::File;
27 use DXVars;
28 use DXUtil;
29 use DXLog;
30
31 use strict;
32
33 my $fp = DXLog::new('debug', 'dat', 'd');
34 my $today = $fp->unixtoj(time()); 
35 my $fh = $fp->open($today) or die $!; 
36 my $nolines = 1;
37 $nolines = shift if $ARGV[0] =~ /^-?\d+$/;
38 $nolines = abs $nolines if $nolines < 0;  
39 my $exp = join '|', @ARGV;
40 my @prev;
41
42 # seek to end of file
43 $fh->seek(0, 2);
44 for (;;) {
45         my $line = <$fh>;
46         if ($line) {
47                 if ($exp) {
48                         push @prev, $line;
49                         shift @prev while @prev > $nolines; 
50                         if ($line =~ m{(?:$exp)}oi) {
51                                 printit(@prev); 
52                                 @prev = ();
53                         }
54                 } else {
55                         printit($line);
56                 }
57         } else {
58                 sleep(1);
59                 
60                 # check that the debug hasn't rolled over to next day
61                 # open it if it has
62                 my $now = $fp->unixtoj(time()); 
63                 if ($today->cmp($now)) {
64                         $fp->close;
65                         my $i;
66                         for ($i = 0; $i < 20; $i++) {
67                                 last if $fh = $fp->open($now);
68                                 sleep 5;
69                         }
70                         die $! if $i >= 20; 
71                         $today = $now;
72                 }
73         }
74 }
75
76 sub printit
77 {
78         while (@_) {
79                 my $line = shift;
80                 chomp $line;
81                 $line =~ s/([\x00-\x1f\x7f-\xff])/sprintf("\\x%02X", ord($1))/eg; 
82                 my ($t, $l) =  split /\^/, $line, 2;
83                 my ($sec,$min,$hour) = gmtime((defined $t) ? $t : time);
84                 my $buf = sprintf "%02d:%02d:%02d", $hour, $min, $sec;
85                 
86                 print $buf, ' ', $l, "\n"; 
87         }
88 }
89 exit(0);