#!/usr/bin/perl -w
#
# This script is copyright 2002 Host Europe Internet Ltd
#
use strict;
require CGI;
my $outpath = $ENV{SCRIPT_FILENAME};
$outpath=~ s/(^.+)logs.cgi$/$1/;
delete @ENV{qw{ENV PATH BASH_ENV}};
$ENV{qw{PATH}}="/bin:/usr/bin:/usr/local/bin";
print CGI::header();
my $sname=CGI::server_name();
$sname =~ m/^.+$/;
my $success=0;
my $app;
if ( -f "/usr/local/bin/webalizer" ) {
  $app="/usr/local/bin/webalizer";
} elsif (-f "/usr/bin/webalizer" ) {
  $app="/usr/bin/webalizer";
}
my $logpath="../../logs/access_log*";
#my $outpath=".";
my $devnull="/dev/null";
for my $logfile (reverse sort glob("$logpath")) {
  # need to redirect stdout/stderr in here
  open(OLDOUT, ">&STDOUT");
  open(OLDERR, ">&STDERR");
  open(STDOUT, '>', "/dev/null") or die "Could not redirect stdout to /dev/null: $!\n";
  open(STDERR, '>', "/dev/null") or die "Could not redirect stderr to /dev/null: $!\n";
  select(STDERR); $| = 1;
  select(STDOUT); $| = 1;
  $success=1 unless my $result = system "$app", "-n$sname", "-p", "-o", "$outpath", "$logfile", "2>&1> $devnull";
  close(STDOUT);
  close(STDERR);
  open(STDOUT, ">&OLDOUT");
  open(STDERR, ">&OLDERR");
  close(OLDERR);
  close(OLDOUT);
}
if($success or -f "webalizer.current") {
print <<EOF;
<html><head><title>Webalizer stats for $sname</title></head>
<frameset rows='*'>
<frame src='.'/>
</frameset>
<noframes>
Click <a href='.'>here</a> to view your stats
</noframes>
</html>
EOF
} else {
print <<EOF;
<html><head><title>Webalizer stats for $sname</title></head>
<body><p>No stats yet</p>
</html>
EOF
}
