#!/usr/bin/perl

use DB_File;
use Fcntl ':flock'; # import LOCK_* constants

# v2
my $prefix =	'/var/www/htdocs/lnk.to';
my $cache_top =   "$prefix/cache_top";
my $cache_last =  "$prefix/cache_last";
my $db =          "$prefix/db";
my $tmp =		  "$prefix/tmp";

my %top;

opendir(DBDIR, $db) or die "opendir: $db: $!\n";
my @files = grep { /\w+/ } readdir(DBDIR);
while ( @files ) {
	$file = shift @files;
	my %h;
	my $killme = 0;
	flock("$db/$file",LOCK_EX);
	tie %h, "DB_File", "$db/$file" or die "tie: $db/$file: $!\n";
	if( $ARGV[0] eq 'entropy' ) {
		if( $h{'score'} < .1 ) {
			$killme++;
		} else {
			$h{'score'} = $h{'score'}/2;
		}
	}
	$top{$h{'key'}} = $h{'score'} unless $killme;
	untie %h;
	flock("$db/$file",LOCK_UN);
	if( $killme ) { print "Removing $file.\n"; unlink "$db/$file"; }
}

open(TOP, ">$cache_top.tmp") or die "open: $cache_top.tmp: $!\n";
my @top = sort { $top{$a} <=> $top{$b} } keys %top;
while( @top ) {
	my $e = pop @top;
	print TOP "$top{$e}\t$e\n";
}
close TOP;
rename "$cache_top.tmp", $cache_top;

if( $ARGV[0] eq 'entropy' ) {
	flock($cache_last,LOCK_EX);
	open(CL,$cache_last) or die "Open: $cache_last: $!";
	open(NCL,">$cache_last.tmp") or die "Open: $cache_last.tmp: $!";
	my @array;
	while( <CL> ) {
		push @array, $_;
	}
	my ($c, $l);
	$l = @array/4;
	while( $c++ < $l ) {
		shift @array;
	}
	while( $l = shift @array ) {
		print NCL $l;
	}
	chmod(0666,"$cache_last.tmp");
	rename "$cache_last.tmp", $cache_last;
	flock($cache_last,LOCK_UN);
	system("ls -l $cache_last");
}
