f133a143448972d0e75e5f019fb9015665ef77ff
[spider.git] / perl / grepdbg
1 #!/usr/bin/perl
2 #
3 # Program to do a grep with dates and times on the debug
4 # files
5 #
6 # grepdbg [nn] [-mm] <regular expression>
7 #
8
9 # nn - is the day you what to look at: 1 is yesterday, 0 is today
10 # and is optional if there is only one argument
11 #
12 # -mmm - print the mmm lines before the match. So -10 will print
13 # ten lines including the line matching the regular expression. 
14 #
15 # <regexp> is the regular expression you are searching for, 
16 # a caseless search is done
17 #
18 #
19
20 require 5.004;
21
22 # search local then perl directories
23 BEGIN {
24         # root of directory tree for this system
25         $root = "/spider"; 
26         $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
27         
28         unshift @INC, "$root/perl";     # this IS the right way round!
29         unshift @INC, "$root/local";
30 }
31
32 use SysVar;
33 use DXUtil;
34 use DXLog;
35 use Julian;
36
37 use strict;
38
39 use vars qw(@list $fp $today $string);
40
41
42 $fp = DXLog::new('debug', 'dat', 'd');
43 $today = $fp->unixtoj(time()); 
44 my $nolines = 1;
45 my @prev;
46
47 for my $arg (@ARGV) {
48         if ($arg =~ /^-/) {
49                 $arg =~ s/^-//o;
50                 if ($arg =~ /^\s*\-+(?:[h\?]e?l?p?)/) {
51                         usage();
52                         exit(0);
53                 }
54                 push @list, $arg;
55         } elsif ($arg =~ /^\d+$/) {
56                 $nolines = $arg;
57         } else {
58                 $string = $arg;
59                 last;
60         }
61 }
62
63 $string ||= '.*';
64
65 push @list, "0" unless @list;
66 for my $entry (@list) {
67         my $now = $today->sub($entry); 
68         my $fh = $fp->open($now); 
69         my $line;
70         if ($fh) {
71                 while (<$fh>) {
72                         process($_);
73                 }
74                 $fp->close();
75         }
76 }
77
78 sub process
79 {
80         my $line = shift;
81         chomp $line;
82         push @prev, $line;
83         shift @prev while @prev > $nolines;
84         if ($line =~ m{$string}io) {
85                 for (@prev) {
86                         s/([\x00-\x1f\x7f-\xff])/sprintf("\\x%02X", ord($1))/eg; 
87                         my ($t, $l) =  split /\^/, $_, 2;
88                         print atime($t), ' ', $l, "\n"; 
89                 }
90                 @prev = ();
91         }
92 }
93         
94 sub usage
95 {
96         die "usage: grepdbg [nn] [[-nnn] ..] <regexp>\n";
97 }
98 exit(0);