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 TokyoCabinet;

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 mkbasedir {
	my $dir = shift;
	$dir =~ s{/[^/]+$}{}; # strip filename
	mkdir $dir unless -e $dir;
}

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

	if ( $data->{file} =~ m{^(.*/)?.sync/send/([^/]+)$} ) {
		my $from_dir = $1;
		warn "SEND $2 from $from_dir\n";
		my $sent_files;
		open(my $send, '<', $self->blob_path($data) );
		while(<$send>) {
			s/[\n\r]+$//;

			my ( $to, $file ) = split(/\s+/,$_,2);
			my ( undef, undef, $uid, $gid, undef, undef, $email, $dir, $shell ) =
				getpwnam $to;

			my $from = $data;
			$from->{file} = $from_dir . $file;
			my $from_path = $self->blob_path($from);

			if ( ! -r $from_path ) {
				warn "ERROR: $from_path: $!";
				next;
			}

			my $to_path = "$dir/received/$file";
			mkbasedir $to_path;

			warn "SEND $from_path -> $to_path\n";
			unlink $to_path if -e $to_path; # FIXME why we need this?
			$sent_files->{$to} += link $from_path, $to_path;
			# FIXME cross-shard
			my $md5 = $self->md5sum($data)->get( $from_dir . $file ) || warn "no md5 for $from_dir$file";
			$self->md5sum({login => $to})->put( "/received/$file" => $md5 );
		}

		warn "SENT ",dump $sent_files;

		return 0; # skip dedup
	} elsif ( $data->{file} =~ m{^(.*/)?.sync/pending/([^/]+)$} ) {
		my $from_dir = $1;
		warn "PENDIG $2 from $from_dir";
		open(my $pend, '<', $self->blob_path($data) );
		while(<$pend>) {
			s/[\n\r]+$//;
warn $_;
			if ( ! /^(MOVED|RENAMED)\#/ ) {
				warn "skip $_\n";
				next;
			}

			my ( undef, $from, $to ) = split(/\#/,$_,3);

			my ( $from_path, $to_path ) = map {
				my $tmp = $data;
				$tmp->{file} = $from_dir . $_;
				$self->blob_path($tmp);
			} ( $from, $to );

			if ( ! -e $from_path ) {
				warn "SKIPPED $from_path: $!";
				next;
			}

			warn "MV $from_path -> $to_path";
			mkbasedir $to_path;
			rename $from_path, $to_path;
	
			my $md5 = $self->md5sum($data)->get( $from_dir . $from );
			if ( ! $md5 ) {
	 			warn "ERROR: no md5sum $from_dir $from " unless $md5;
				next;
			}

			$self->md5sum($data)->out( $from_dir . $from );
			$self->md5sum($data)->put( $from_dir . $to => $md5 );

			warn "$md5 moved to $from_dir $to";
		}

		return 0; # skip dedup
	}

	#return $file->{size} > 4096 ? 1 : 0; # FIXME
	return 1; # dedup
}

# never called by rsync directly!
sub new_file {
	my ( $self,$data ) = @_;
#	$self->file_set($data);
}

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

	my $md5 = $self->md5sum($data)->get( $data->{file} );
	return unless $md5; # directories don't have md5sums
	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";
	}

	$self->md5sum($data)->out( $data->{file} );
}

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 $md5 = $self->md5sum($data)->get($s);
				$self->md5sum({ login => $to })->put($d => $md5 );
				# FIXME broken!
			}


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

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

	my $login = $data->{login} || confess "missing login in ",dump $data;

	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 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;

		foreach my $login ( keys %{ $self->{md5sum} } ) {
			$self->{md5sum}->{$login}->close;
			warn "close md5sum $login";
		}
		delete $self->{md5sum};

		delete $self->{pid}->{$pid};
		warn "removed $pid";
warn dump $self;

	} 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 ) && # selective dedup
			$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);
	} else {
		warn "IGNORED ",dump($data) if $ENV{DEBUG};
	}
	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";
		warn "dedup +++ $md5 $path";
	}

	$self->md5sum($data)->put( $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;
