#!/usr/bin/perl
#
# Package Name    : twhttpd
# File Name       : rm_cache
# Author          : Sam NG <samng@computer.org>
#
# This package is an secure HTTP application proxy writen by Sam Ng.
# Copyright (C) 2001 SAM NG
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software 
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, 
# MA  02111-1307, USA.

use strict;

#####################################################################
# YOU HAVE TO MODIFY THE FOLLOWING IN ORDER TO MAKE IT WORKS
#
# NOTE: I will retain $max_cache (bytes) in $cache_dir
#       Therefore, the cache size may growth above this limit
#       until you run this script on next time
#####################################################################
my $max_cache=100*1024*1024;
my $cache_dir="/your/twhttpd/cache/path";

#####################################################################
# you seldom need to change anything below                          #
#####################################################################
my $LS="/bin/ls";
my $test=0;                     # not really delete the file, just try to see what would happen
my $debug=0;                    # print out a lot of debug messages, you won't want to enable this

sub main
{
    my @raw_list;               # raw output of the "ls"
    my @list_tb;                # file list table
    my %list_id;                # file list index
    my $pname;                  # the other file name for the header/body pair
    my $saved_size=0;           # total size of all handled files
    my $saved_n=0;
    my $size2;                  # total size of header/body files
    my $all_size=0;             # total size of all input files
    my $all_n=0;
    my $del_size=0;             # total size of all deleted files
    my $del_n=0;
    my ($i, $j); 
    my ($fname, $fsize);
    my ($f1, $f2, $f3, $f4, $f5, $f6, $f7, $f8, $f9);
    my $tmp_str;
    my $tmp;

    open(LIST, "$LS -ltu $cache_dir |");
    @raw_list=<LIST>;
    close(LIST);

    # decode the data first
    $j = @raw_list;
    $tmp = 0;
    for( $i=0; $i<$j; $i++ )
    {
        # drwxr-xr-x 2 root root 4096 Feb 6 2000 dir1
        # -rwxr-xr-x 1 root root 1234 Nov 12 2001 file123
        ($f1, $f2, $f3, $f4, $f5, $f6, $f7, $f8, $f9) = split(/\s+/, $raw_list[$i]);

        # ignore everything which is not file type
        if ( $f1 =~ /^-/ )
        { 
            push(@list_tb, "$f9|$f5");
            $list_id{$f9} = $tmp;
            $tmp++;
            $all_size += $f5;
            $all_n++;
        }
    }
    
    # OK, now I get list_table and list_id
    $j = @list_tb;
    
    #for ( $i=0 ; $i<$j ; $i++ )
    #{
    #    print "[tb $i]: $list_tb[$i]\n";
    #}
    #while ( ($fname,$fsize) = each %list_id )
    #{
    #    print "[index]: $fname|$fsize\n";
    #}
    #return;
    
    for ( $i=0 ; $i<$j ; $i++ )
    {
        ($fname, $fsize) = split(/\|/, $list_tb[$i]);
        
        # only if size >= 0, size < 0 means already handled
        if ( $fsize >= 0 )
        {
            if ( $fname =~ /(.*)\.header$/ )
            {
                # header file
                $pname = $1;
                
            }
            else
            {
                # cache body file
                $pname = $fname.".header";
            }
            #print "[$i] Original File: $fname\n";
            #print "[$i] Pair File    : $pname\n";
            
            $size2 = $fsize;
            $tmp = $list_id{$pname};
            
            ($tmp_str, $fsize) = split(/\|/, $list_tb[$tmp]);
            
            if ( $tmp_str ne $pname )
            {
                if ( $tmp <= 0 )
                {
                    if ( $debug )
                    {
                        print "Orphan File found\n";
                        print "unlink $cache_dir/$fname\n";
                    }
                    if ( !$test) 
                    {
                        unlink "$cache_dir/$fname" || print "error remove file: $?\n";
                    }
                    if ( $fsize > 0 ) { $del_size += $fsize; }
                    $del_n++;
                }
                else
                {
                    # probably program error
                    print "File name not match, $tmp_str:$pname\n";
                }
            }
            elsif ( $fsize < 0 )
            # $fsize < 0 means file already handled
            # but this should not be the case, as the prevous one
            # should have already disable THIS record
            {
                if ( $debug )
                {
                    print "Unmatch pair: $fname $size2\n";
                    print "            : $pname $fsize\n";
                }
            }
            else
            # should be OK now
            {
                $size2 += $fsize;
                
                if ( $saved_size + $size2 < $max_cache )
                {
                    # let this header/body file pair pass
                    $list_tb[$i] = "$fname|-1";
                    $list_tb[$tmp] = "$pname|-1";
                    if ( $debug > 1 )
                    {
                        print "Saved $size2 bytes\n";
                        print "keep $cache_dir/$fname\n";
                        print "keep $cache_dir/$pname\n";
                    }
                    $saved_size += $size2;
                    $saved_n += 2;
                }
                else
                {
                    # kill them ALL!!!!
                    $list_tb[$i] = "$fname|-1";
                    $list_tb[$tmp] = "$pname|-1";
                    if ( $debug )
                    {
                        print "Remove $size2 bytes\n";
                        print "unlink $cache_dir/$fname\n";
                        print "unlink $cache_dir/$pname\n";
                    }
                    if ( !$test )
                    {
                        unlink "$cache_dir/$fname" || print "error removing $fname: $?\n";
                        unlink "$cache_dir/$pname" || print "error removing $pname: $?\n";
                    }
                    $del_size += $size2;
                    $del_n += 2;
                }
            }
        }
    }
    
    print "Original: $all_size bytes in $all_n files\n";
    print "Saved   : $saved_size bytes in $saved_n files\n";
    print "Deleted : $del_size bytes in $del_n files\n";
}

&main;
exit;
