#!/usr/bin/env perl

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

my $filename = shift(@ARGV);
my $key = shift(@ARGV) or die("DB file name and key expected\n");
my $null = shift(@ARGV);

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 {
	    $key .= chr(0) if ($null eq '-0');
	    if ($database{$key}) {
	        delete($database{$key});
	    } else {
	        print(STDERR "record with key '$key' not found in db file '$filename'\n");
	    }
        }
	$db->sync();
        close(DATAFILE);
    }
    undef($db);
    untie(%database);
}
