package CloudStore::MD5sum;
use warnings;
use strict;

use TokyoCabinet;
use Carp qw(confess carp);

sub new {
	my ($class) = @_;
	my $self = {};
	bless $self, $class;
	return $self;
}

our $md5sum_db;

sub md5sum {
	my ( $self, $data ) = @_;

	my $login = $data;
	   $login = $data->{login} if ref $data eq 'HASH' && exists $data->{login};

	return $md5sum_db->{$login} if exists $md5sum_db->{$login};

	my ( undef, undef, $uid, $gid, undef, undef, $email, $dir, $shell ) =
		getpwnam $login;

	my $md5_path = "$dir/.md5";

	my $db = TokyoCabinet::HDB->new();
	$db->open($md5_path, $db->OWRITER | $db->OCREAT)
	or die "can't open $md5_path: ",$db->errmsg( $db->ecode );

	warn "open $md5_path";

	$md5sum_db->{$login} = $db;
	return $db;
}

sub md5sum_dump {
	my ( $self, $login ) = @_;

	my @lines;

	my $hdb = $self->md5sum( $login );
        $hdb->iterinit();
        while(defined(my $key = $hdb->iternext())){
            my $value = $hdb->get($key);
            if(defined($value)){
		push @lines, "$value  $key";
            }
        }
	return @lines;
}


sub md5sum_close {
	my ( $self, $login ) = @_;

	$login = $login->{login} if ref $login eq 'HASH';
	confess "no login" unless $login;

	if ( exists $md5sum_db->{$login} ) {
		$md5sum_db->{$login}->close;
		delete $md5sum_db->{$login};
		warn "close md5sum $login";
	} else {
		carp "# close md5sum $login IGNORED";
	}
}

1;
