#!/usr/bin/env perl
use 5.006;
use strict;
use warnings;

use JSON;
use File::Find;
use Net::Plywood::Simple;
use Getopt::Long;
use Pod::Usage;
use Try::Tiny;

my ($dir, $file, $key, $scheme, $host, $port, $help, $man);
GetOptions(
	'dir=s'    => \$dir,
	'file=s'   => \$file,
	'key=s'    => \$key,
	'scheme=s' => \$scheme,
	'host=s'   => \$host,
	'port=s'   => \$port,
	'help|?'   => \$help,
	man        => \$man,
) or die("Error in command line arguments\n");
pod2usage(1) if $help;
pod2usage(-exitval => 0, -verbose => 2) if $man;
pod2usage(1) unless (($file || $dir) && $key && $host && $port);
pod2usage(1) if ($file && $dir);

my $data;
if ($file) {
	open(my $json_fh, '<:encoding(UTF-8)', $file)
		|| die("Can't open $file: $!\n");
	my $json_text = <$json_fh> || '0';
	close($json_fh);
	my $json = JSON->new;
	try {
		$data = $json->decode($json_text);
	} catch {
		die("Can't decode JSON in $file: $_\n");
	};
} elsif ($dir) {
	$data = indexFileSystem($key, $dir);
}

my $plywood = Net::Plywood::Simple->new(
	scheme => ($scheme || 'http'),
	host   => $host,
	port   => $port,
);

my $res = $plywood->put($key, $data);

print "... uploaded index to $host with key $key\n";

sub indexFileSystem {
	my ($key, $dir) = @_;
	my $index       = {};
	find(
		sub {
			return if -l;
			$File::Find::name =~ s/$dir//;
			my @keys = split('/', $File::Find::name);
			shift(@keys);
			my $node = $index;
			while( my $part = shift @keys ) {
				if (@keys) {
					$node->{$part} ||={};
					$node = $node->{$part};
				}
				else {
					if (-f $_) {
						$node->{$part}  = [];
						my $data        = {};
						@{$data}{qw(mode size atime mtime ctime)} = (stat($_))[2,7,8,9,10];
						$data->{mode} &&= sprintf("%o", $data->{mode});
						$data->{size} &&= 0+$data->{size};
						$data->{key}    = $key;
						push(@{$node->{$part}}, $data);
					}
					else {
						$node->{$part} ||={};
					}
				}
			}
		},
		($dir),
	);
	return $index;
}

1;

__END__

=USAGE

USAGE:

	plywood-simple-put [options] [arguments]

Examples:

	With JSON file:
		plywood-simple-put --file test.json --key test123 --host localhost --port 8080

	To take an index of a directory:
		plywood-simple-put --dir /path/to/dir --key test123 --host localhost --port 8080

=cut

