#!/usr/bin/perl

# This shows a slide show on ALL available framebuffers

# The last item on the command line should be the path to the pictures
# other options are "file" for file handle mode, "error" for show
# errors, and 'auto' for autolevel.

use strict;
use threads;
use threads::shared;

use Graphics::Framebuffer;
# use Data::Dumper::Simple;

my $args = join('',@ARGV);

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

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

my @fbs;
foreach my $p (qw(/dev/graphics/fb /dev/fb)) {
    foreach my $b (0..31) {
        push(@fbs,"$p$b") if (-e "$p$b");
    }
}

my $RUNNING : shared = 1;
$SIG{'QUIT'} = sub {
    print STDERR "\nExiting..\n";
    $RUNNING = 0;
};
$SIG{'INT'} = sub {
    print STDERR "\nExiting..\n";
    $RUNNING = 0;
};

our @pics : shared;

my @f;
foreach my $fb (@fbs) {
    push(@f,Graphics::Framebuffer->new(
        'FB_DEVICE'   => $fb,
        'SPLASH'      => 1,
        'SHOW_ERRORS' => $errors,
        'FILE_MODE'   => $file
    ));
}

gather($ARGV[-1]);

# print STDERR Dumper(\@pics);exit;

my @thr;

foreach my $F (@f) {
    push(@thr,threads->create(
        sub {
            my $FB = shift;
            my $p  = shift;
            system('clear');
            $FB->cls('OFF');

            show($FB,$p);
            $FB->cls('ON');
        },
        $F,
        scalar(@pics)
    ));
}
while($RUNNING) {
    sleep 1;
}
foreach my $t (@thr) {
    $t->join();
}
exit(0);


sub gather {
    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") {
            gather("$path/$file");
        } elsif (-f "$path/$file" && $file =~ /\.(jpg|jpeg|gif|tiff|bmp|png)$/i) {
            push(@pics,"$path/$file");
        }
    }
}

sub show {
    my $FB = shift;
    my $p  = shift;
    while ($RUNNING) {
        my $name = $pics[int(rand($p))];
        my $image = $FB->load_image(
            {
                'width' => $FB->{'XRES'},
                'height' => $FB->{'YRES'},
                'file' => $name,
                'center'=> $FB->{'CENTER_XY'},
                'autolevels' => $auto
            }
        );
        if (defined($image)) {
            $FB->cls();
            $FB->blit_write($image);
            sleep 3;
        }
    }
}
