#!/usr/bin/perl
use File::Copy;

$config = '/etc/httpd/conf/httpd.conf';

open (CONF, $config) || die "Was unable to open $config: $!\n";
while (<CONF>) {
   if (/^Use vhost/) {
     (undef,undef,undef,$domain,$user,$ext,$aliases) = split/\s+/;
      $DocumentRoot = "/home/$ext/$user/public_html";
      $CustomLog = "/var/log/httpd/$domain";
      $ServerName = $domain;
      next unless ($ServerName && $DocumentRoot && $CustomLog);
      print "$ServerName ... ";
      mkdir "$DocumentRoot/webstats/" if (!-d "$DocumentRoot/webstats/");
      if (-e "/home/$ext/$user/webalizer.conf") {
        system "webalizer -c /home/$ext/$user/webalizer.conf";
#        print "webalizer -c /home/$ext/$user/webalizer.conf\n";
      } else {
        system "webalizer -r *$ServerName* -n $ServerName -o $DocumentRoot/webstats/ $CustomLog";
#       print "webalizer -r *$ServerName* -n $ServerName -o $DocumentRoot/webstats/ $CustomLog\n";
      }
      copy ("/dev/null","$CustomLog") || print "Error reseting log file: $CustomLog - $!\n";
      print "ok\n";
     next;
   }
   if (/^<VirtualHost\s+(.+)>/) {
	$vhost = $1;
	$vhost_section = 1;
	($DocumentRoot,$ServerAdmin,$ServerName,$CustomLog) = undef;
   }
   if ($vhost_section == 1) {
	$DocumentRoot = $1 if (/DocumentRoot\s+(.+)/);
#	$ServerAdmin  = $1 if (/ServerAdmin\s+(.+)/);
	$ServerName   = $1 if (/ServerName\s+(.+)/);
	$CustomLog    = $1 if (/CustomLog\s+(.+)\s+combined$/);
	if (/<\/VirtualHost>/) {
	  $vhost_section = 0;
	  $ServerName = $vhost if (!$ServerName);
	  next unless ($ServerName && $DocumentRoot && $CustomLog);
	  print "$ServerName ... ";
	  mkdir "$DocumentRoot/webstats/" if (!-d "$DocumentRoot/webstats/");
          if (-e "$DocumentRoot/../webalizer.conf") {
            system "webalizer -c $DocumentRoot/../webalizer.conf";
#             print "webalizer -c $DocumentRoot/../webalizer.conf\n";
          } else {
#             print "webalizer -r *$ServerName* -n $ServerName -o $DocumentRoot/webstats/ $CustomLog\n";
             system "webalizer -r *$ServerName* -n $ServerName -o $DocumentRoot/webstats/ $CustomLog";
	  }
	  copy ("/dev/null","$CustomLog") || print "Error reseting log file: $CustomLog - $!\n";
	  print "ok\n";
	}
   }
}
close CONF;

