#!/usr/pkg/bin/perl

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

use CGI::Tools;
use CGI::QueryString;

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

################################################################
TDS::Admin::Authorize->PrintHTTPHeader();

my $logdir = GetLogDir();
my $title = "Clear Log Files";
my $auth = new TDS::Admin::Authorize;

if (param('command') eq 'clear'){
    $auth->CheckPassword(param('password'));
    print qq(<title>$title</title>);
    print qq(<h1>$title</h1>);

    for (param()){
	my $file = UrlDecode($_);

	if ($file =~ /^clear_(.*)$/){
	    $file = $1;
	    unlink("$logdir/$file") || print "can't clear $logdir/$file";
	    print "clear: $file<br>";
	} elsif ($file =~ /^gzip_(.*)$/){
	    $file = $1;
	    `gzip $logdir/$file`;
	    print "gzip: $file<br>";
	} elsif ($file =~ /^gunzip_(.*)$/){
	    $file = $1;
	    `gunzip $logdir/$file`;
	    print "gunzip: $file<br>";
	}
    }
} else {
    $auth->CheckAuthorized;
    
    print qq(<title>$title</title>);
    print qq(<h1>$title</h1>);
    opendir(LOGDIR, $logdir) || die $logdir;
    print qq(<form action="clear_log.cgi" method="post">);
    print qq(<table border=1>\n);
    print qq(<tr><th>clear<th>gzip<th>gunzip<th>file<th>size);
#    while ($file = readdir(LOGDIR)){
    for (sort readdir(LOGDIR)){
	my $file = $_;
	next if $file =~ /^\./;
#	print join(',', stat("$logdir/$file"));
	my $for_gzip;
#	nless ($file =~ /\.gz$/){
	if ($file =~ /\.log$/){
	    $for_gzip = qq(<input type="checkbox" name=gzip_$file>);
	}
	my $for_gunzip;
	if ($file =~ /\.gz$/){
	    $for_gunzip = qq(<input type="checkbox" name=gunzip_$file>);
	}
	printf(qq(<tr>
		  <td><input type="checkbox" name=clear_%s>
		  <td>%s
		  <td>%s		  
		  <td>%s<td>%s<br>\n),
	       $file, $for_gzip, $for_gunzip, $file, (stat("$logdir/$file"))[7]);
    }
    print qq(</table>);
    print qq(<input type="hidden" name="command" value="clear">);
#    print qq(<input type="radio" name="method" value="clear" checked>clear<br>);
#    print qq(<input type="radio" name="method" value="gzip">gzip<br>);
    print qq(Password: <input type="password" name="password"><br>);
    print qq(<input type="submit" value="OK">);
    print qq(<input type="reset" value="Reset">);
    print qq(</form>);
}
print qq(<hr><a href="./">admin</a>);

