package CloudStore::API;
use warnings;
use strict;
use autodie;

use lib 'lib';
use base qw(CloudStore::Gearman);

use File::Path qw(make_path remove_tree);
use File::Find;
use Data::Dump qw(dump);

sub new {
	my ($class,$group) = @_;

	my ( undef, $dir, $port, undef ) = getgrnam($group) || die "can't find group $group: $!";
	my $self = {
		passwd => '/var/lib/extrausers/passwd',
		PORT => $port,
		SLICE => $dir,
	};
	bless $self, $class;

	$self->{md5} = $self->user_info('md5');

	return $self;
}

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

	my @n = qw/ login passwd uid gid quota comment gecos dir shell expire /;
	my @p = $login =~ m/^\d+$/ ? getpwuid $login : getpwnam $login;
	my $user;
	$user->{$_} = shift @p foreach @n;
	return $user;
}

sub create_user {
	my ( $self, $new_email, $new_passwd, $new_quota ) = @_;

	my $max_uid = 0;
	my $found = 0;

	open(my $fh, '<', $self->{passwd});
	while(<$fh>) {
		my ( $login, $passwd, $uid, $gid, $email, $dir, $shell ) = split(/:/,$_);
		$max_uid = $uid if $uid > $max_uid;
		$found = $uid if $email eq $new_email;
	}
	close($fh);

	if ( ! $found ) {
		$max_uid++;
		my $dir = "$self->{SLICE}/$max_uid";
		warn "# create_user $new_email $new_quota = $max_uid $dir";
		open(my $fh, '>>', $self->{passwd});
		print $fh "u$max_uid:$new_passwd:$max_uid:$self->{PORT}:$new_email:$dir:/bin/true\n";
		close($fh);
		$found = $max_uid;

		mkdir $dir;
		chown $max_uid, $self->{PORT}, $dir;

	}

	# FIXME update quota only on create?
	$self->gearman_do( 'narada_s1_quota_set' => "$found $new_quota" );

	return $found;
}

sub mkbasepath {
	my ($path,$opts) = @_;
	$path =~ s{/[^/]+$}{};
	make_path $path unless -d $path;
}

sub user_dir {
	my ( $self,$user, $dir ) = @_;
	$user = $self->user_info($user) unless ref $user eq 'HASH';
	my $path;
	if ( exists $user->{dir} ) {
		$path = $user->{dir} . '/' . $dir;
	} else {
		die "no dir in ", dump $user;
	}
	$path =~ s{//+}{/}g;
#	warn "## user_dir $path";
	return $path;
}

sub append {
	my $self = shift @_;
	my $user = shift @_;
	my $path = $self->user_dir( $user => '.log');
	my $line = join('#',@_);
	open(my $fh, '>>', $path);
	print $fh "$line\n";
	close $fh;
	warn "## $path $line\n";
	$user = $self->user_info($user) unless ref $user eq 'HASH';
}

sub usage {
	my ( $self, $user ) = @_;
	$user = $self->user_info($user) unless ref $user eq 'HASH';
	my $path = $self->user_dir( $user => '.log');
	my $sum;
	open(my $fh, '<', $path);
	while(<$fh>) {
		chomp;
		my @v = split(/#/,$_);
		$sum->{ $v[0] } += $v[1];
		$sum->{_usage}  += $v[1];
	}
	my ( $usage, $quota ) = split(/ /,
		$self->gearman_do( 'narada_s1_quota_get' => $user->{uid} )
	);
	$sum->{_usage} += $usage;
	$sum->{_quota} = $quota;
	warn "## usage ",dump($user, $sum), $/;
	return $sum;
}

sub send_file {
	my ( $self, $f_uid,$f_path, $t_uid,$t_path ) = @_;

	my $f = $self->user_info($f_uid);
	my $t = $self->user_info($t_uid);

	my $f_full = "$f->{dir}/$f_path";
	my $t_full = "$t->{dir}/$t_path";

	mkbasepath $t_full, { uid => $t->{uid} };

	my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat $f_full;
	if ( $uid == $f->{uid} ) {
		warn "# send_file - move $f_uid $f_path to pool\n";
		chown $self->{md5}->{uid}, $self->{md5}->{gid}, $f_full;
		chmod oct("0444"), $f_full;
		$self->append( $f, 'sent', -s $f_full, $t->{uid}, $f_path );
	} elsif ( $uid == $self->{md5}->{uid} ) {
		warn "# send_file - shared $f_full\n";
	}

	$self->delete( $t, $t_path ) if -e $t_full;

	link $f_full, $t_full; 
	$self->append( $t, 'recv', -s $t_full, $f->{uid}, $t_path );
}

sub rename_file {
	my ( $self, $user, $from, $to ) = @_;
	$user = $self->user_info($user) unless ref $user eq 'HASH';

	$self->append( $user, 'rename', $from, $to );
}


sub delete {
	my ( $self, $user, $path ) = @_;
	$user = $self->user_info($user) unless ref $user eq 'HASH';

	my $deleted_size = 0;
	my $full_path = "$user->{dir}/$path";

	if ( -d $full_path ) {

		find({ 
		no_chdir => 1,
		wanted => sub {
			return if -d $_;
			my ($uid,$size) = (stat($_))[4,7];
			warn "## find $uid $size $_\n";
			if ( $uid == $self->{md5}->{uid} ) {
				$deleted_size += $size;
			}
		}}, $full_path);

		remove_tree $full_path;
	} else {
		$deleted_size += -s $full_path;
		unlink $full_path;
	}

	warn "delete $deleted_size bytes shared\n";

	$self->append( $user, 'delete', -$deleted_size, $user->{uid}, $path );
}

1;
