#!/usr/bin/perl
use warnings;
use strict;
use POSIX qw(mkfifo);

# fifimage
# Run this script and then read (e.g. with 'cat') from the fifo
# and it will read a random jpg file from the image directory
# Cameron Hayne (macdev@hayne.net)  July 2004

die "Usage: fifimage: name_of_fifo image_directory\n" unless scalar(@ARGV) == 2;
my $fifoName = $ARGV[0];
my $imageDir = $ARGV[1];

# Function declarations:
sub getImageFiles($);
sub chooseFile(@);

# ---- MAIN ----

my @imageFiles = getImageFiles($imageDir);

while (1)
{
    unless (-p $fifoName)
    {
        unlink($fifoName);
        mkfifo($fifoName, 0666) or die "can't mkfifo $fifoName: $!";
    }

    # next line blocks until there's a reader
    open(FIFO, "> $fifoName") or die "can't write $fifoName: $!";
    print "Somebody is reading from the fifo $fifoName\n";
    my $file = chooseFile(@imageFiles);
    print "Chosen file is $file\n";
    open(FILE, "< $file") or die "Can't open file $file for reading: $!";
    while (<FILE>)
    {
        print FIFO $_;
    }
    close(FILE);
    print "Closing fifo\n";
    close(FIFO);

    sleep 2; # to avoid dup signals
}

# ---- FUNCTIONS ----

sub getImageFiles($)
{
    my ($imageDir) = @_;

    my @imageFiles = ();
    opendir(DIR, $imageDir) or die "can't opendir $imageDir: $!";
    while (defined(my $file = readdir(DIR)))
    {
        next if $file =~ /^\.\.?$/;     # skip . and ..

        if ($file =~ /\.jpg$/)          # suffix is .jpg
        {
            my $pathname = "$imageDir/$file";
            push(@imageFiles, "$pathname") if -r $pathname;
        }
    }
    closedir(DIR);

    return @imageFiles;
}

sub chooseFile(@)
{
    my (@files) = @_;

    my $numFiles = scalar(@files);
    my $index = int(rand($numFiles));
    my $file = $files[$index];
    return $file;
}

