#!/usr/bin/env perl

# Copyright (C) 2006  Joshua Hoblitt
#
# $Id: dsget,v 1.4 2007-09-26 21:58:25 jhoblitt Exp $

use strict;
use warnings FATAL => qw( all );

use vars qw( $VERSION );
$VERSION = '0.01';

use DataStore;
use File::Temp ();
use File::Basename qw( basename dirname );

use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
use Pod::Usage qw( pod2usage );

my ($uri, $bytes, $md5, $nebulous, $filename, $node, $server);

$server = $ENV{'NEB_SERVER'} unless $server;

GetOptions(
    'uri|u=s'       => \$uri,
    'bytes|m=s'     => \$bytes,
    'nebulous|n'  => \$nebulous,
    'node|n=s'      => \$node,
    'server|s=s'    => \$server,
    'md5|m=s'       => \$md5,
    'filename|f=s'  => \$filename,
) or pod2usage( 2 );

pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
pod2usage(
    -msg => "Required options: --uri --filename",
    -exitval => 3,
) unless defined $uri and defined $filename;

my %p = (
    uri     => $uri,
    type    => 'chip',
);

$p{bytes} = $bytes if defined $bytes; 
$p{md5sum} = $md5 if defined $md5;

# can we truely write to filename?
{
    # open file for ready/write but not create
    my $fh;
    if (open($fh, '+<', $filename)) {
        # do nothing and fall through
    } elsif (open($fh, '>>', $filename)) {
        unlink $filename or die "can't unlink $filename: $!";
    } else {
        die "can't write to $filename";
    }
}

my $tmp = File::Temp->new(
    DIR         => dirname($filename),
    TEMPLATE    => '.' . basename($filename) . 'XXXX',
    SUFFIX      => '.tmp',
    UNLINK      => 1,
);

my $tmpfilename = $tmp->filename;

my $response = DataStore::File->new(%p)->request( filename => $tmpfilename );

die "request failed" unless defined $response;
die "request failed: ", $response->status_line unless $response->is_success;

# file retreival succeed

# this can't cross a file system boundry so we can assume that a move will
# always be a rename operation instead of a copy and delete.

if ($nebulous) {
    require Nebulous::Client;
    require File::Copy;
    my $neb = Nebulous::Client->new(
        proxy   => $server,
    );

    die "can't connected to Nebulous Server: $server"
        unless defined $neb;

    my $fh = $neb->open_create( $filename, $node )
        or die "Nebulous can't create key $filename";
    open(my $src_fh, $tmpfilename) or die "can't open file $tmpfilename: $!";

    File::Copy::copy( $src_fh, $fh ) or die "file copy failed";

    close($src_fh) or die "can't close file $tmpfilename: $!";
    close($fh) or die "can't close nebulous filehandle";
} else {
    rename $tmpfilename, $filename
        or die "renaming $tmpfilename to $filename failed: $!";
}

__END__

=pod

=head1 NAME

gsget - download a file from a DataStore server

=head1 SYNOPSIS

    dsget --uri <uri> --filename <filename> [--bytes <nbytes>] [--md5 <hex>]

=head1 DESCRIPTION

=head1 OPTIONS

=over 4

=item * --uri|-u <uri>

The URI of the file to be retrieved.

=item * --filename|-f <filename>

The name to use when writing the file to disk.

=item * --bytes|-s <nbytes>

The size of the file in bytes.

Optional, the size check is skipped if no value is specified.

=item * --md5|-m <hex>

The md5 checksum of the file in hex.

Optional, the md5check is skipped if no value is specified.

=back

=head1 CREDITS

Just me, myself, and I.

=head1 SUPPORT

Please contact the author directly via e-mail.

=head1 AUTHOR

Joshua Hoblitt <jhoblitt@cpan.org>

=head1 COPYRIGHT

Copyright (C) 2006  Joshua Hoblitt.  All rights reserved.

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.  See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA  02111-1307, USA.

The full text of the license can be found in the L<perlgpl> Pod as supplied
with Perl 5.8.1 and later.

=head1 SEE ALSO

L<DataStore>, L<DataStore::File>

=cut
