# G-RIN database handling.
# Copyright (C) 1999 Ian Jackson <ijackson@chiark.greenend.org.uk
#
# This 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,
# or (at your option) any later version.
#
# This 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 file; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

@db_fields= qw(network prefix name contact email hiddenemail created changed);

sub read_database () {
print DEBUG "reading\n";
    my (@v,$id);
    open DBF, "list" or die $!;
    for (;;) {
	$_= <DBF>;
	length or die "$_ $!";
	s/\n$//;
	last if m/^\002/;
	@v= split(/\001/,$_);
	$id= shift @v;
	length $id or die;
	undef $v;
	foreach $f (@db_fields) { $v->{$f}= shift(@v).''; }
	$db{$id}= $v;
    }
    close DBF or die $!;
    $db_read= 1;
}

$db_lock_env= 'BCP5REGISTRY_LOCKED';

sub write_database () {
    my ($k,$v);
print DEBUG "writing\n";
    die unless $ENV{$db_lock_env};
    open DBF, ">list.new" or die $!;
    while (($k,$v) = each %db) {
	$str= "$k";
	foreach $f (@db_fields) { $str.= "\1".$v->{$f}; }
	print DBF $str,"\n" or die $!;
    }
    print DBF "\2\n" or die $!;
    close DBF or die $!;
    rename "list.new","list" or die $!;
}

sub lock_database () {
print DEBUG "locking\n";
    die if $db_read;
    return if $ENV{$db_lock_env};
    $ENV{$db_lock_env}= '1';
    exec 'with-lock-ex','-w','lockfile',"$0",@org_argv;
    die "$ENV{'PATH'}: $!";
}

1;
