### perl: poros/code/dump

use strict;
use warnings;
use File::Temp;
use Digest::MD5;

return sub
{
    my %param = @_;
    for my $conf ( ref $param{argv}[0] ? @{ $param{argv} } : $param{argv} )
    {
        my $path = delete $conf->{path};
        my ( $fh, $temp ) = File::Temp::tempfile();
        my $unlink = sub { unlink shift; return 1 };

        return 1 unless defined $conf->{md5}
            && $path && $fh && length $conf->{file};

        return 1 if $conf->{chown} && ! ( my @pw = getpwnam $conf->{chown} );

        print $fh $conf->{file};
        seek $fh, 0, 0;
        my $md5 = Digest::MD5->new()->addfile( $fh )->hexdigest;
        close $fh;

        return &$unlink( $temp ) if $md5 ne $conf->{md5};
        return &$unlink( $temp ) if system "mv $temp $path";
        return &$unlink( $path ) if $conf->{chmod}
            && ! chmod oct $conf->{chmod}, $path;
        return &$unlink( $path ) if @pw && ! chown @pw[2,3], $path;
    }

    print "ok\n";
    return 0;
};
