#!/usr/bin/perl -w

# Copyright (c) 2008 Miek Gieben
# See LICENSE for the license

# todo; robustness, error checking
use strict;
use Net::Amazon::S3;

use Getopt::Long;
use File::Basename;
use File::Temp qw{tempdir tempfile};
use POSIX;

# common functions
my $prefix="/usr";
my $datarootdir = "${prefix}/share";
require "${datarootdir}/rdup/shared.pl";

my $progName = basename $0;
my %opt;
my $s3;

# connect to amazon
# key id, secret key
sub s3connect($$) {
    my $s3 = Net::Amazon::S3->new( 
	{
	aws_access_key_id => shift,
	aws_secret_access_key => shift,
	}
    );
    if (! $s3) {
        die "** $progName: Could not connect to S3";
    }
    $s3;
}

# get a file from a bucket
# bucket, filename, localname
sub s3get($$$) {
    my $bucket = shift;
    my $response = $bucket->get_key_filename(shift, 'GET', shift)
}

# bucket, filename, localname
sub s3put($$$) {
    my $bucket = shift;
    my $response = $bucket->add_key_filename(shift, shift,
	    {  content_type => 'application/binary', },
	    ) or die "** $progName: Upload failed: " . $s3->errstr . "\n";
}

# create a bucket
# s3 obj, bucket name (string)
sub s3bucket($$) {
    my $s3 = shift;
    my $response = $s3->add_bucket( { bucket => shift } ) or 
	    die $s3->err . ": " . $s3->errstr;
    # check the error, if the bucket is already there
    # its ok, otherwise it is now created :-)
    # TODO
}

# bucket object
# return 2 refs to arrays
sub s3list_files($) {
    my $bucket = shift;
    my $r = $bucket->list_all or die "** $progName: can't get a file listing";
    foreach ( @{ $r->{keys} } ) {
	printf "%15d %s\n", $_->{size}, $_->{key};
    }
}

# return a list of buckets
# s3 object
sub s3list_buckets($) {
    my $s3 = shift;
    my $r = $s3->buckets;

    @ { $r->{buckets} };
}

# remove file from bucket, or the bucket itself
# s3 conn, bucketname, filename
sub s3rm($$;$) {
    my ($s3, $b, $file) = (shift, shift, shift);
    if ($file) {
	# remove it
	my $bucket = $s3->bucket($b);
	$bucket->delete_key($file) or die
	    "** $progName: can not remove $file " . $s3->errstr;
    } else {
	$s3->delete_bucket({ bucket =>$b}) or
	    die "** $progName: can not remove the bucket " . $s3->errstr;
    }
}

# options
# -b bucketname
# -k keyid_file
# -s secret_key_id_file
# then:
# up | get | rm | ls  [filename]
# where filename is remote name

my ($bucket, $help, $version, $key, $secret);
GetOptions('b=s' => \$b,
	   'i=s' => \$key,
	   'k=s' => \$secret,
	   'h'	 => \$help,
	   'V'	 => \$version
	);
version($progName) if $version;
usage() if $help || !$key || !$secret;

# re-use the names
my $i = 0;
foreach ($key, $secret) {
    open IN, "<", $_ or die "** $progName: Can not open: " . $_;
	my $a = <IN>; # only the first line is read
	chomp $a;
    close IN;
    $key = $a if $i == 0;
    $secret = $a if $i == 1;
    $i++
}

$s3 = s3connect $key, $secret; # dies on failure

# next we have are command, get, put, rm, ls 
# and maybe a filename
# for get and put we need one, for rm and ls
# we can ignore the file, in that case we list
# the bucket. If we also don't have a bucket we 
# list all the files in the bucket

my %ops = qw/get 1 put 1 rm 1 ls 1/;
if (! $ops{lc $ARGV[0]} ) {
    die "** $progName: No valid command given";
} 
my $O = lc shift;

if ($O eq "get" || $O eq "put") {
    if (! $ARGV[0] ) {
	die "** $progName: A filename is required with \`get' and \`put'";
    }
    if (! $b) {
	die "** $progName: A bucket name is required";
    }
    s3bucket $s3, $b; # create one or 
    my $bucket = $s3->bucket($b);

    # if we have a filename argument, this isn't exactly needed
    my $tmpDir = tempdir("rdup.s3.XXXXXX", TMPDIR => 1, CLEANUP => 1);
    die "** $progName: Could not create:" . " $tmpDir: $!" unless -d $tmpDir;
    my ($n, $buf, $file);
    my $localname = "$tmpDir/rdup.$$.s3";
    # GET, get a file and cat it
    if ($O eq "get") {
	# TODO errors
        my $response = $bucket->get_key_filename($ARGV[0], 'GET', $localname) or 
	    die "** $progName: failed to retrieve file";
	catfile($localname);
	unlink $localname;
    }
    # PUT, save all stdin in the file and upload it
    if ($O eq "put") {
	open OUT, "> $localname" or die "** $progName: Could not open:" . " $localname: $!";
	while (($n = read STDIN, $buf, 4096) > 0) {
	    syswrite OUT, $buf, $n;
	}
	close OUT;
	s3put $bucket, $ARGV[0], $localname;
	unlink $localname;
    }
    exit 0;
}

if ($O eq "ls") {
    if (! $b) {
	# no bucket given, list them all
	my @buckets = s3list_buckets $s3;
	foreach (@buckets) {
	    print $_->bucket, "\n";
	}
    } else {
	my $bucket = $s3->bucket($b);
	# only usage of this function, let it print the stuff there
	s3list_files $bucket;
    }
    exit 0;
}

# remove stuff
if ($O eq "rm") {
    die "** $progName: Need at a bucket name when removing" unless $b;
    if (!$ARGV[0]) {
	# remove the bucket
	s3rm $s3, $b;
    } else {
	s3rm $s3, $b, $ARGV[0];
    }
    exit 0;
}

sub usage {
        print "$progName [-b BUCKET] -i ID -k SECRET [OPTIONS] put|get|rm|ls [FILENAME]\n\n";
        print "Manipulate files and buckets from Amazon's S3 service\n\n";
	print " put   upload a file\n";
	print " get   download a file and cat it\n";
	print " rm    remove a file or bucket\n";
	print " ls    list files or buckets\n";
	print "\nOPTIONS\n";
	print "-b BUCKET  name of the bucket to use\n";
	print "-i ID      file containing your S3 id\n";
	print "-k SECRET  file containing your private S3 key\n";
        print "-c         ignored as rdup-s3 always works on content\n";
        print "-h         this help\n";
        print "-V         print version\n";
        exit;
}
