#! /usr/bin/perl

#                            W I N D U P
#                           Windex Update

#            by John Walker  --  http://www.fourmilab.ch/
#                This program is in the public domain

#   This Perl script examines a list of directories named on
#   the command line to see if files have been added since the
#   last time windex was run to create the image index for that
#   directory.  If one or more images have been added, windex
#   is invoked to update the index.

#   Options:
#       -a      Update all directories, regardless of whether
#               they appear to have current indices.
#
#       -n      Dry run: print directories to be updated,
#               but do not actually update them.

#   Bugs: windup does not detect when an image is removed.  The
#   index will contain a broken link to the removed image until
#   adding a new image causes a full index update.

    use strict;
    use warnings;

    my $pwd = `pwd`;
    my $all = 0;
    my $dryrun = 0;
    my $dir;

    foreach $dir (@ARGV) {
        if ($dir eq '-a') {
            $all = 1;
        } elsif ($dir eq '-n') {
            $dryrun = 1;
        } else {
        print(STDERR "$dir: ");
            if (chdir($dir)) {
                my $lastfile = `ls -t1 | head -1`;
                if ((!$all) && $lastfile =~ m/^(index\.html|Index-.*\.jpg)/) {
                    print(STDERR "up to date.\n");
                } else {
                    print(STDERR "changed, updating...\n");
                    if ($dryrun) {
                        print(STDERR "    ...well, not really.  This is a dry run.\n");
                    } else {
                        system("windex *");
                    }
                }
                chdir($pwd);
            } else {
                print(STDERR "Cannot access directory $dir: $!\n");
            }
        }
    }
