#!/usr/pkg/bin/perl
# $Id: refresh_counter.cgi,v 1.9 2000/10/18 16:51:42 tom Exp $
################################################################

use strict;
use lib qw(../lib);

use vars qw($GZIP $WC $GREP);

use CGI::Tools;

use TDS;
use TDS::System;
use TDS::AccessLog::Counter;
use TDS::AccessLog::DirInfo;
use TDS::Admin::Authorize;

$GZIP = "gzip";
$WC = "wc";
$GREP = "grep";

$| = 1;

################################################################
my ($total, $today) = (0, 0);
my $ymd;
my ($n_day, $n_month, $n_year) = (localtime(time()))[3..5];
$n_year += 1900;
$n_month++;
$ymd = sprintf("%04d/%02d/%02d", $n_year, $n_month, $n_day);

TDS::Admin::Authorize->PrintHTTPHeader;

my $msg;

my $auth = new TDS::Admin::Authorize;
$auth->CheckAuthorized;

#print $ymd;
my $logdir = GetLogDir();
{
    opendir(DIR, $logdir) || die;
    my @files = readdir(DIR);
    for (sort @files){
	my $filename = "$logdir/$_";
	if (/^(\d{4})\-(\d{2})\.log(\.gz)?$/){
	    $msg .= "logfile: $filename: ";
	    #print "logfile: $filename\n";
	    my ($year, $month) = ($1, $2);
	    my $is_gziped = $3;

	    #print "$year, $month\n";
	    my $is_this_month = ($n_year == $year && $n_month == $month);
	    #print "this month: $is_this_month\n";
	    my $num;
	    unless ($is_gziped){
		$num = (split(" ", `$WC -l $filename`))[0];
	    } else {
		$num = (split(" ", `$GZIP -cd $filename | $WC -l`))[0];
	    }
	    $msg .= "$num<br>\n";
	    $total += $num;
	    if ($is_this_month){
		$today = (split(" ", `$GREP '$ymd' $filename | $WC -l`))[0];
	    }
	}
    }
}

{
    my $counter = new TDS::AccessLog::Counter;
    $counter->Set($total, $today);
}
{
    print qq(<html><head><title>Refresh Counter Files</title>
	     </head>
	     <body>
	     <h1>Refresh Counter Files</h1>
	     <p>
	     $msg
	     </p>
	     <p>
	     total access: $total<br>
	     today\'s access: $today
	     </p>
	     <hr>
	     <a href="./">admin</a>
	     </body>
	     </html>
	     );
}
