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

use TokyoCabinet;
use Carp qw(confess);

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

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

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

	return $self->{md5sum}->{$login} if exists $self->{md5sum}->{$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";

	$self->{md5sum}->{$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 ) = @_;

	my @logins;
#           @logins = keys %${ $self->{md5sum} } if exists $self->{md5sum} and ref $self->{md5sum} eq 'HASH';
	   @logins = ( $login ) if $login;

	foreach my $login ( @logins ) {
		# FIXME only login's?
		$self->{md5sum}->{$login}->close;
		warn "close md5sum $login";
	}
	delete $self->{md5sum};
}

1;
