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

use MYDan;
use YAML::XS;
use Digest::MD5;
use MYDan::Agent::FileCache;

local $/ = undef;

my %param = %{ YAML::XS::Load( <> ) };

my $conf = $param{argv};

my $path = delete $conf->{path};

my $idie = sub{ print shift;exit 1; };
my $unlink = sub { unlink shift; print shift; exit 1 };

&$idie( "MYDanExtractFile undef" ) unless my $MYDanExtractFile = $ENV{MYDanExtractFile};

my $tmp = "$MYDan::PATH/tmp";
unless( -d $tmp ){ mkdir $tmp;chmod 0777, $tmp; }
$tmp .= '/dump.data.';
for my $f ( grep{ -f } glob "$tmp*" )
{
    my $t = ( stat $f )[9];
    unlink $f if $t && $t < time - 3600;
}

my $temp = $tmp. Digest::MD5->new->add( sprintf "$path.%d.%stmp",  time, $$ )->hexdigest;

&$idie( 'param error' ) unless defined $conf->{md5} && $path;
&$idie( "get $conf->{chown} uid fail" ) if $conf->{chown} && ! ( my @pw = getpwnam $conf->{chown} );

&$unlink( $temp, "copy fail: $!" ) if system "cp '$MYDanExtractFile' '$temp'";
open my $fh, "<$temp" or &$idie( "Open MYDanExtractFile fail: $!" );
my $md5 = Digest::MD5->new()->addfile( $fh )->hexdigest;
close $fh;

&$unlink( $temp, 'chomd fail' ) if $conf->{chmod}
     && ! chmod oct $conf->{chmod}, $temp;
&$unlink( $temp, 'chown fail' ) if @pw && ! chown @pw[2,3], $temp;

&$unlink( $temp, 'md5 nomatch' ) if $md5 ne $conf->{md5};
&$unlink( $temp, 'rename fail' ) if system "mv '$temp' '$path'";

eval{ MYDan::Agent::FileCache->new()->save( $path ); };
print "filecache save fail:$@" if $@;
print "ok\n";
exit 0;
