#!/usr/bin/perl
#
# Recursively walks httpd.conf for Include directives not being part of a
# VirtualHost. Returns all configfiles so defined.
#
# Pierfrancesco Caci, ik5pvx - Same licence as apache itself.
#
use warnings;
use strict;
use diagnostics;

my $baseconfig=$ARGV[0];
my $serverroot = "/";

scanfile($baseconfig);

print "\n";

exit 0;

sub scanfile {
  my $file = $_[0];

  print "$file ";

  open (my $conf,'<',$file) or warn "Can't open config file $file.\n$!\n";

  skipvirtual($conf);

  close $conf

}


sub skipvirtual {
  my $cfg = $_[0];
 OUTER: while (<$cfg>) {

    next if /^\s*$/;
    next if /^\s*\#/;

    if (/^\s*<virtualhost/i) {
    INNER: while (<$cfg>) {
#	print "DEBUG: $_";
	last INNER if /^\s*<\/virtualhost/i;
      }
    }

    next if /^\s*<\/virtualhost/i;

    if (/^\s*serverroot/i) {
      s/^\s*(.*)/$1/;
      (undef,$serverroot) = split;
      ($serverroot .= "/") unless ($serverroot =~ m|/$|);
#      print "DEBUG: Found ServerRoot to be $serverroot\n";
    }

    if (/^\s*include/i) {
      s/^\s*(.*)/$1/;
      my (undef,$file) = split;

      if ($file !~ m|^/| ) {
	$file = $serverroot . $file;
      }


      testfile($file);
    }
  }

}


sub scandir {
  my $dir = $_[0];
  my $glob = $_[1];
#  print "DEBUG: working on $dir with regexp $glob\n";
  opendir (DIR, $dir) or warn "Can't open directory $dir\n$!\n";
  my @files = grep (!/^\.{1,2}$/ && /^$glob$/, readdir(DIR));
#  print "DEBUG: found @files\n";
  closedir DIR;
  foreach (@files) {
    testfile("$dir/$_");
  }
}


sub testfile {
  my $path = $_[0];
  
  if ( $path =~ /[*?]/) {
#    print "DEBUG: fileglob found: $path\n";
    $path =~ m|^(/.*/)(.*)$|;
    my $dir = $1;
    my $glob = $2;
    $dir =~ s|(.*)/$|$1|;
    $glob =~ s/\./\\\./g;
    $glob =~ s/\*/\.\*/g;
    $glob =~ s/\?/\.{1}/g;
#   print "DEBUG: expanding parent dir $dir, looking for glob $glob\n";
    scandir ($dir,$glob);
  } else {
    if ( -d $path ) {
      #	print "DEBUG: found directory $path\n";
      scandir($path,'.*');
    } elsif ( -f $path ) {
      #	print "DEBUG: found plain file $path\n";
      scanfile($path);
    } elsif ( -e $path and -r $path ){
      warn "You tried to include something that is neither file nor directory: $path\n";
    } else {
      warn "Can't read $path\n$!\n";
    }
    #      print "DEBUG: $path\n";
  }
}
