#!/usr/bin/perl

# A very simple gallery-maker that creates listing for just one directory.
# Use "-t" to sort pictures by timestamp rather than name, and use -N <num>
# to control the number of pictures on a row.

use strict;
use warnings;

use Cwd;
use File::Basename 'basename';
use Getopt::Std;
use Image::Size qw(imgsize);

our $cmd = basename $0;
our $VERSION = '1.0';
our $timesort = 0;
our $now = scalar localtime;
our %opts;

getopts('tN:', \%opts);

our $dir = shift(@ARGV) || cwd;
$timesort++ if $opts{t};
our $columns = $opts{N} || 4;

opendir(our $dh, $dir) or die "Error opening $dir: $!, stopped";
our @images = grep(/\.(:?jpg|jpeg|gif|png)$/i, readdir($dh));
closedir $dh;

if ($timesort) {
    @images = sort { (lstat $a)[9] <=> (lstat $b)[9] } @images;
} else {
    @images = sort @images;
}

# Output the boilerplate part of the XHTML
$dir = basename $dir;
print <<"EO_Header";
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Image Gallery - $dir</title>
    <meta name="created" content="$now" />
    <meta name="generator" content="$cmd $VERSION" />
  </head>
  <body>
EO_Header
print "    <h1>Image Gallery - $dir - " . scalar(@images) . " item" .
    ((@images == 1) ? '' : 's') . "</h1>\n    <hr />\n    <table>\n";

while (@images) {
    print "      <tr>\n";
    for (1 .. $columns)     {
        my $image = shift @images;
        unless ($image)         {
            print "        <td></td>\n";
            next;
        }
        my ($width, $height) = imgsize($image);
        my ($theight, $twidth);
        if ($height > $width) {
            if ($height <= 200) {
                $theight = $height;
                $twidth = $width;
            } else {
                $theight = 200;
                $twidth = $width * (200 / $height);
            }
        } else {
            if ($width <= 200) {
                $theight = $height;
                $twidth = $width;
            } else {
                $twidth = 200;
                $theight = $height * (200 / $width);
            }
        }

        print qq(        <td><a href="$image"><img src="$image" ) .
            qq(width="$twidth" height="$theight" alt="$image" /></a></td>\n);
    }
    print "      </tr>\n";
}

print <<"EO_Foot";
    </table>
    <hr />
    <div style="text-size: 80%">
      <i>Generated by $cmd v$VERSION on $now</i>
    </div>
  </body>
</html>
EO_Foot

exit;