#!/usr/bin/perl

# by samy [CommPort5@LucidX.com]
# This some-what 'greps' all input files you give it with
# the string to 'grep', and if it sees any #include's in
# the files (usually in C and header files), it will also
# 'grep' those for the string, and everything in those,
# and everything in those, and so on :)

if (@ARGV < 2) {
 die "usage: $0 [-g (case-insensitive)] <list of C/header files> <'string/regexp to perl grep'>\n";
}

$grep = pop(@ARGV);
if ($ARGV[0] =~ /^-.{1}$/) {
 $arg = shift(@ARGV);
}

foreach $file (@ARGV) {
 $check{$file} = 1;
}
foreach $file (@ARGV) {
 $bad = 0;
 open(TMP, "<$file") or $bad++;
 if ($bad) {
  print "Unable to open $file: $!\n";
 }
 else {
  while (<TMP>) {
   if ($arg eq "-g") {
    if (/$grep/i) {
     print "$file:$_";
    }
   }
   else {
    if (/$grep/) {
     print "$file:$_";
    }
   }
   if (/include\s*<([^>]+)>/ and !$check{"/usr/include/" . $1}) {
    $incl{"/usr/include/" . $1} = 1;
    $check{"/usr/include/" . $1} = 1;
   }
  }
  close(TMP);
 }
}

&dcheck(%incl);

sub dcheck {
 %temp = @_;
 %new = ();
 foreach $file (keys(%temp)) {
  $check{"/usr/include/" . $file} = 1;
 }
 foreach $file (keys(%temp)) {
  $bad = 0;
  open(TMP, "<$file") or $bad++;
  if (!$bad) {
   while (<TMP>) {
    if (/include\s*<([^>]+)>/ and !$check{"/usr/include/" . $1}) {
     $new{"/usr/include/" . $1} = 1;
     $check{"/usr/include/" . $1} = 1;
    }
    if ($arg eq "-g") {
     if (/$grep/i) {
      print "$file:$_";
     }
    }
    else {
     if (/$grep/) {
      print "$file:$_";
     }
    }
   }
   close(TMP);
  }
 }
 if (%new) {
  &dcheck(%new);
 }
}
