package Parp::Friends;

=head1 NAME

Parp::Friends - friends database management

=head1 SYNOPSIS

Used internally.

=head1 DESCRIPTION

This module provides routines for managing the database of known
friends.

=cut

use strict;
use warnings;

use DB_File;
use Fcntl qw(:DEFAULT);

use Parp::Config qw(config);
use Parp::Utils qw(check_file_dir fatal error);
use Parp::Locking;

use base qw(Exporter);
our @EXPORT_OK = qw(is_friend make_friend break_friend);

my %friends = ();

use constant LOCK_IDENT => 'Friends';

sub attach {
  my $db = config->friends_db;
  check_file_dir($db);
  lock_ident(LOCK_IDENT);
  tie %friends, 'DB_File', $db, O_RDWR | O_CREAT, 0600
    or fatal "Failed to tie $db as Berkeley DB: $1\n";
}

sub release {
  # Avoid `1 inner references still exist' warnings
  my $tied = tied %friends ? 1 : 0;
  $tied and untie %friends;
  unlock_ident(LOCK_IDENT);
}

sub is_friend { $friends{$_[0]} }

sub make_friend {
  my ($new_friend, $reason) = @_;
  tied %friends or error "%friends no longer tied?!\n";
  $friends{$new_friend} = $reason;
}

sub break_friend {
  my ($ex_friend) = @_;
  delete $friends{$ex_friend};
}

END {
  release();
}


1;
