#!/usr/bin/perl

## Locate each virtualhost entry and run webalizer in its directory
## Configure each line according to needs, remove the $CFGLOCK entry when
## you have.

## Leigh Morresi <leigh@linuxbandwagon.com>

$CFG_FILE="/etc/httpd/conf/httpd.conf";
$WEBALIZER="/usr/local/bin/webalizer";
$AUTOLOGFILE="/var/log/auto-webalizer.log";
$CFGLOCK="yes";


## There probably isnt much of interest past here.

if ( $CFGLOCK) {
    die "Please configure me correctly, i will now die.";
}

logmessage ("auto-webalizer begin");

$inside=0;
$sc=0;

open (CFGFILE,$CFG_FILE) or die "Could not open config file, have you configured this correctly? $?";
while(<CFGFILE>) {
chomp $_;


    if (  /^\<VirtualHost/mi) {
	$inside=1;
    }

    if ( ( /^\<VirtualHost/mi)  && ($inside==1) ) {
	    ## Find what value the documentroot is

	    if ( (/DocumentRoot/i) ||  (/CustomLog/i) ) {
		($null,$docroot)=split(/DocumentRoot\ /i,$_);
	    }
	    
	    ## Find what value the log file is
	    if (/TransferLog/i) {
		$_=~s/\ common//ig;
		($null,$logfile)=split(/TransferLog\ /i,$_);
	    }
	    
	    #found the closing bracket? time to process that entry
	    if ( /^\<\/VirtualHost/m ) {
		$inside=0;
		
		#Does the docroot exist?
		if ( stat($docroot) ) { 
		    $dir="$docroot/stats/";
		    mkdir($dir,0777);
		    logmessage("$dir created chmod to 0777.");
		}
		
		# if we can change to the stats dir, and the logfile exists
		if ( chdir($dir)  && ( stat($logfile) )  ) {
		    $cmd ="cat $logfile|$WEBALIZER -p -t $docroot -n $logfile";
		    system($cmd) or die "Error running ($cmd), cannot continue.\n";
		    $sc=$sc+1;
		} else {
		    print STDERR "Could not change to dir $docroot/stats/, check that it exists\n";
	        }
	    #clear
	    $docroot="";
    	    $logfile="";
	    } else {
		$inside=1;
	    }

        }
    
}

close(CFGFILE);

logmessage("$sc sites were webalized, auto-webalizer finished");

sub logmessage  {

    $message=shift;
    open (AUTOLOGFILE,">>$AUTOLOGFILE") or die "Could not open log file for appending to $AUTOLOGFILE.";
    $now_string = localtime;
    print AUTOLOGFILE "$now_string: $message\n";    
    close(AUTOLOGFILE);
}
