#!/usr/bin/perl

# A simple utility to view a picture from the command line
#
# The first option should be the file name to show
# The (optional) second option is 'mali' if a MALI GPU.

use strict;

use Graphics::Framebuffer;

my $args = join('',@ARGV);
my $dev = 0;
if ($args =~ /(\d+)/) {
    $dev = $1;
}

my $file = 0;
$file = 1 if ($args =~ /file/i);

my $errors = 0;
$errors = 1 if ($args =~ /errors/i);

my $f = Graphics::Framebuffer->new(
    'FB_DEVICE'   => "/dev/fb$dev",
    'SPLASH'      => 1,
    'SHOW_ERRORS' => $errors,
    'FILE_MODE'   => $file
);

system('clear');
$f->cls();

show($ARGV[-1]);

sub show {
    my $path = shift;

    opendir(my $DIR,$path);
    chomp(my @dir = readdir($DIR));
    closedir($DIR);

    foreach my $file (@dir) {
        next if ($file =~ /^\.+/);
        if (-d "$path/$file") {
            show("$path/$file");
        } elsif (-f "$path/$file" && $file =~ /\.(jpg|jpeg|gif|tiff|bmp|png)$/i) {
            my $image = $f->load_image(
                {
                    'width'  => $f->{'XRES'},
                    'height' => $f->{'YRES'},
                    'file'   => "$path/$file"
                }
            );
            if (defined($image)) {
                $f->cls();
                $f->blit_write($image);
                sleep 3;
            }
        }
    }
}
