package Imager;
use 5.010;
use strict;
use warnings;
use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
use autodie qw(:all);
use if $^V >= v5.18 => (experimental => 'smartmatch');

our $VERSION = "0.1";

use constant CIPHER => "aes-128-cbc";

sub get_file {
    my ($base) = @_;
    foreach (map { "$base$_" } "", qw/.gz .x .gz.x/) {
	return $_ if -f;
    }
}

sub get_block {
    my ($file, $buffer) = @_;

    $file = get_file($1) if $file =~ /(.*)\*$/;

    given ($file) {
        when (/\.gz\.x$/) {
            open(my $fh => "openssl @{[CIPHER]} -d -pass $::o{pass} -in $file|");
            gunzip($fh => $buffer) or die $GunzipError;
        }
        when (/\.gz$/) { gunzip($file => $buffer) or die $GunzipError }
        when (/\.x$/) {
            open(my $fh => "openssl @{[CIPHER]} -d -pass $::o{pass} -in $file|");
            $$buffer = <$fh>;
        }
        default { open(my $fh => $file); sysread $fh => $$buffer, -s $fh }
    }
}

1;
