#!/usr/bin/perl
use 5.016;

# This script requires the Ubuntu package libimage-exiftool-perl
# or the Homebrew package exiftool. If it's missing, try to output
# helpful installation instructions.
push @INC, '/usr/local/opt/exiftool/libexec/lib'
    if  -d '/usr/local/opt/exiftool/libexec/lib';  # for Homebrew
eval {
  require Image::ExifTool;
};
if ($@) {
    my $cmd;
    if ($^O eq 'linux') {
        my $sudo = 'sudo';
        $sudo = 'cl-asuser' if -x '/usr/bin/cl-asuser';
        if (-x '/usr/bin/apt-get') {
            $cmd = "$sudo apt-get install libimage-exiftool-perl";
        }
    } elsif ($^O eq 'darwin') {
        if (-x '/usr/local/bin/brew') {
            $cmd = "brew install exiftool";
        } else {
            print STDERR (
                "$_ requires the Perl library Image::ExifTool.\n",
                "One way to get it is by first installing Homebrew\n",
                "from https://brew.sh/ and then “brew install exiftool”\n"
                );
        }
    }
    if ($cmd) {
        print STDERR "\n\x1b[1mPlease run this shell command ",
            "to install a required library\n",
            "(or ask your system administrator):\n\n",
            "\$ \x1b[32m$cmd\x1b[m\n\n";
        exit 1;
    } else {
        die $@;
    }
}

my $width = 310;

while ($ARGV[0] =~ /^-/) {
    my $opt = shift @ARGV;
    if ($opt = '-w') {
        $width = shift @ARGV;
    } else {
        die("unknown option '$opt'!\n");
    }
}

print <<'EOT';
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<!-- FILE AUTO-GENERATED BY Makefile, DO NOT EDIT -->
<title>Posters</title>
<style>
img.poster { border: 1px solid; float: left; clear: none; margin: 0.5em 1em 0.5em 0 }
h2 { clear: both }
</style>
<h1>Posters</h1>
<p>Here are some of the posters that decorate our corridor.
Click on each image to read the respective PDF version.
EOT

# sort descending by year, but ascending within year
my @posters = sort { substr($b, 0, 4) cmp substr($a, 0, 4) ||
                     substr($a, 4) cmp substr($b, 4)} @ARGV;

my $old_year;
for my $fn (@posters) {
    my $basename = $fn;
    $basename =~ s/\.pdf\z//i;

    # read exif metadata
    my $info;
    $info = Image::ExifTool::ImageInfo($fn);
    my $title = $info->{Title};
    $title =~ s/^Microsoft Word - (.+)\.docx?\z/$1/;
    $title =~ s/_/ /g;
    my $alt = $fn;
    $alt = $title
        if $title && $title !~ /Microsoft Word/ && $title !~ /\.[a-z]{1-8}\z/;
    $alt =~ s/"/&quot;/g;

    my $year = $1 if $fn =~ /^(\d\d\d\d)/;
    if ($year ne $old_year) {
        say qq{<h2 id="y$year">$year</h2>};
        $old_year = $year;
    }

    say qq{<a href="$fn"><img src="$basename.png" alt="$alt" width="$width" class="poster"></a>};
}
