#!/usr/bin/perl

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

my $filename = shift(@ARGV);
my $ttl = shift(@ARGV) or die("DB file name and expire period (in min) expected\n");

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 {
	    $ttl *= 60;
	    my($key, $deleted);
	    foreach $key (keys(%database)) {
	    	my($year, $month, $mday, $hour, $min, $sec);
	    	if (($year, $month, $mday, $hour, $min, $sec) = ($database{$key} =~
		    /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/)) {
		    $year = $year - 1900;
		    $month--;
		    my($datetime) = timelocal($sec, $min, $hour, $mday, $month, $year);
		    ($sec, $min, $hour, $mday, $month, $year) = (localtime)[0,1,2,3,4,5];
		    if (timelocal($sec, $min, $hour, $mday, $month, $year) - $datetime > $ttl) {
		        delete($database{$key});
		        $deleted++;
		    }
		}
	    }
	    print("$deleted expired record(s) deleted\n") if ($deleted);
        }
	$db->sync();
        close(DATAFILE);
    }
    undef($db);
    untie(%database);
}
