#!/usr/bin/env perl

use strict;
use DB_File;
use Fcntl ':flock';
use Time::Local;

my $filename = shift(@ARGV) or die("DB file name expected\n");
my $expire_time_field = shift(@ARGV);
$expire_time_field = "record_expires" unless ($expire_time_field);

my(%database);
my($db) = tie(%database, 'DB_File', $filename, O_CREAT | O_RDWR, 0644);
unless ($db) {
    print(STDERR "couldn't init DB '$filename': $!\n");
} else {
    my($fd) = $db->fd();
    unless (open(DATAFILE, "+<&=$fd")) {
        print(STDERR "couldn't safety open DB '$filename': $!\n");
    } else {
        unless (flock(DATAFILE, LOCK_EX)) {
	    print(STDERR "couldn't lock DB '$filename': $!\n");
	} else {
	    my($key, $deleted, $record_expires);
	    my($sec, $min, $hour, $mday, $month, $year) = (localtime)[0,1,2,3,4,5];
	    my($now) = timelocal($sec, $min, $hour, $mday, $month, $year);
	    foreach $key (keys(%database)) {
	    	if (($record_expires) = ($database{$key} =~ /$expire_time_field=(\d+)/)) {
		    if ($record_expires < $now) {
		        delete($database{$key});
		        $deleted++;
		    }
		}
	    }
	    print("$deleted expired record(s) deleted\n") if ($deleted);
        }
	$db->sync();
        close(DATAFILE);
    }
    undef($db);
    untie(%database);
}
