package CloudStore::Store;
use warnings;
use strict;

use autodie;
use JSON::XS;
use File::Path qw(make_path);
use File::Slurp qw();
use Digest::MD5 qw(md5_base64);
use Data::Dump qw(dump);
use Carp qw(confess);
use BerkeleyDB;

use WarnColor;

sub new {
	my $class = shift;

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

	die "no dir" unless $self->{dir};
	$self->{md5pool} = $self->{dir} . '/md5';

	warn "# new ",dump $self if $ENV{DEBUG};

	return $self;
}

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

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

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

#	if ( my $old = $self->file_get( $data ) ) {
#		$self->usage_decr( $data );
#	}

	$self->new_file($data);
}

sub new_file {
	my ( $self,$data ) = @_;
#	$self->file_set($data);
#	$self->usage_incr($data);
}

sub remove_file {
	my ( $self, $data ) = @_;
#	$self->usage_decr( $data );

	my $md5sum = $self->md5sum($data);
	if ( ! exists $md5sum->{ $data->{file} } ) {
		warn "ERROR: no md5 for ",dump $data;
		return;
	}
	my $md5 = $md5sum->{ $data->{file} };
	my $path = $self->{md5pool} . '/' . $md5;
	my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
		$atime,$mtime,$ctime,$blksize,$blocks)
			= stat($path);
	if ( $nlink == 1 ) {
		my $id = getpwnam 'md5';
		chown $id,$gid, $path;
		warn "# chown $id $gid $path";
	}
}

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

}

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

	warn "# new_link ",dump $data;

	if ( $data->{file} =~ m{^(.*/?)\.send/([^/]+)/(.+)$} ) {
		my ( $dir, $to, $name ) = ( $1, $2, $3 );
		my $path = $self->blob_path($data);
		my $link_to = readlink $path;
		warn "$link_to";
		if ( $link_to =~ s{^\Q/rsyncd-munged/\E}{/} ) {

			my $s = $path;
			$s =~ s{/[^/]+$}{}; # strip filename
			while ( $link_to =~ s{/../}{/} ) {
				$s =~ s{/[^/]+$}{} || die "can't strip $s";
				warn "## simplify $s $link_to\n";
			}
			$s .= $link_to;

			my $d = $self->blob_path({
				pid => $data->{pid},
				file => $name
			});

			# $name can contain directories so we must create them
			my $to_dir = $d;
			$to_dir =~ s{/[^/]+$}{};
			make_path $to_dir if ! -e $to_dir;

			if ( ! -e $s ) {
				warn "ERROR: can't find source $s";
			} else {

				warn "link $s -> $d\n";
				link $s, $d;

				my ($l,$f) = ($1,$2) if $s =~ m{users/([^/]+)/blob/(.+)};

#				my $origin = $self->file_get({
#					login => $l,
#					file  => $f,
#				});
#				$self->new_file($origin);
				warn "INFO: sent file ",dump($l,$f);
				my $md5sum = $self->md5sum($data);

				my $md5 = $md5sum->{$s} || die "no md5 for $s";
				$md5sum->{$d} = $md5; # FIXME broken!
			}


		} else {
			warn "ERROR: can't SEND To:$to Name:$name Link:$link_to";
		}
	}
}

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

	if ( exists $md5_login->{$data->{login}} ) {
		return $md5_login->{$data->{login}};
	} elsif ( my $login = $data->{login} ) {

		my $md5_path = $self->{dir} || die "no dir?";
		$login =~ s/^u//;
		$md5_path .= "/$login/.md5.db";

		my %md5;
		my $db = tie %md5, 'BerkeleyDB::Hash',
			-Filename => $md5_path,
			-Flags => DB_CREATE,
		;

		return $md5_login->{$login} = \%md5;
	} else {
		confess "can't open md5sum";
	}
}

sub rsync_log {
	my ( $self, $data ) = @_;
	if ( $data =~ m/\[(\d+)\] rsync \w+ (\S+) \w+ (\S+)/ ) {
		my ( $pid, $module, $login ) = ( $1, $2, $3 );

		$login =~ s/\@.+//;
		my ( undef, undef, $uid, $gid, undef, undef, $email, $dir, $shell ) =
			getpwnam $login;

		$self->{pid}->{$pid} = {
			login => $login,
			uid => $uid,
			gid => $gid,
			email => $email,
			dir => $dir,
			shell => $shell,
		};

		warn "created $pid";

	} elsif ( $data =~ m/\[(\d+)\] sent \S+ bytes\s+received \S+ bytes/ ) {
		my $pid = $1;
		untie $md5_login->{ $self->{$pid}->{login} } && warn "untie $pid";
		delete $self->{pid}->{$pid};
		warn "removed $pid";
	} else {
#		warn "## rsync_log $data";
	}
}

sub blob_path {
	my ( $self, $data ) = @_;
	my $blob = $self->{pid}->{ $data->{pid} }->{dir} || die "no dir for $data->{pid} in ",dump( $self->{pid} );
	$blob .= '/' . $data->{file};
	return $blob;
}


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

        my $path = $self->blob_path($data);

	if ( $data->{itemize} =~ m/^[c>]([fdL])/ ) { # received change/create
		my $type = $1;

		if ( $type eq 'f' ) {
			$self->modify_file( $data );
			$self->dedup( $data, $path );
		} elsif ( $type eq 'd' ) {
			$self->make_dir( $data );
		} elsif ( $type eq 'L' ) {
			$self->new_link( $data );
		} else {
			die "unknown type $type ", dump $data;
		}
	} elsif ( $data->{itemize} =~ m/\*deleting/ ) {
		$self->remove_file($data);
	}
	return $data;
}

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

	my $pool = $self->{md5pool} || die "no md5pool in ",dump $self;
	mkdir $pool unless -e $pool;

	my $md5 = $data->{md5} || die "no md5 in ",dump $data;
	my $path = $self->blob_path($data);

	if ( -e "$pool/$md5" ) {
		warn "dedup hit $md5 $path\n";
		my $dedup = $path . '.dedup';
		rename $path, $dedup;
		link "$pool/$md5", $path;
		unlink $dedup;
		# FIXME fix perms?
	} else {
		link $path, "$pool/$md5";
	}

	my $md5sum = $self->md5sum($data);
	$md5sum->{ $data->{file} } = $md5;
}

my $empty_md5 = " " x 32;

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

	if ( $data->{file} =~ /^(.+\/)?md5sum$/ ) {
		my $dir = $1;
		my $imported = 0;
		warn "IMPORT ", $data->{file}, "\n";
		open(my $md5sum, '<', $path);
		while(<$md5sum>) {
			chomp;
			my ( $md5, $file ) = split(/\s+/,$_,2);
			if ( ! -e "$self->{md5path}/$md5" ) {
				warn "MISSING $md5 $file\n";
				next;
			}
			my $new = {
				pid => $data->{pid},
				file => "$dir$file",
				md5 => $md5,
			};
			my $new_path = $self->blob_path($new);
			if ( ! -e $new_path ) {
				# create path from md5sum file
				my $only_dir = $1 if $new =~ m{^(.+)/[^/]+$};
				make_path $only_dir unless -d $only_dir;
				$imported += link "$self->{md5path}/$md5", $new_path;
				$self->new_file($new);
				warn "import from $path ",dump($new);
				$self->md5pool( $new );
			} else {
				$self->md5pool( $new );
			}
		}
		print "INFO imported $imported files from ",dump($data);
	}

	if ( $data->{md5} ne $empty_md5 ) {
		$self->md5pool( $data );
	} else {
		warn "empty md5", dump $data;
	}
}

1;
