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

use Data::Dump qw(dump);

sub new {
	my $class = shift;
	my $self = {@_};
	bless $self, $class;

	$self->{passwd} ||= '/var/lib/extrausers/passwd';
	$self->{PORT}   ||= $ENV{PORT}  || die "no PORT in env";
	$self->{SLICE}  ||= $ENV{SLICE} || die "no SLICE in env";

	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;
warn "## $login ",dump(@p);
	die "$login: $!" if $!;
	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;
	}

	return $found;
}

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

	
}

sub rename_file {
	my ( $uid, $from, $to ) = @_;
}


sub delete {
	my ( $uid, $path ) = @_;

}

sub usage {
	my ( $uid ) = @_;

}

1;
