#!/usr/bin/perl -w
#---------------------------------------------------------------------------------------------------------
# show_thumbs.pl - this lists the contents of a folder of photos as clickable thumbnails
#                    written by Eric Pence
#---------------------------------------------------------------------------------------------------------
use strict;
use CGI qw(-oldstyle_urls :standard);
use CGI::Carp qw(fatalsToBrowser);

# Define global variables
use vars qw($curr_dir $log_file);

#---------------------------------------------------------------------------------------------------------
# Grab the current directory from $0. The following regular expression
# looks for 'CURR_DIR\xxxxx.xxx' or 'CURR_DIR/xxxxx.xxx'. Place it in
# the BEGIN block so we can use it to include modules
#---------------------------------------------------------------------------------------------------------
BEGIN {
  $0 =~ '(.*[\\\/])\w+\.\w+$';
  $curr_dir = $1 || "./";

  # Set up error log file
  $log_file = "error_log.txt";
  use CGI::Carp qw(carpout);
  open(LOG, ">>${curr_dir}${log_file}")
        or die "Unable to append to error log: $!";
  carpout(*LOG);
}

use lib ( $curr_dir );
use FileHandle;

my $q = new CGI;
my $photo_directory = $q->param('photos');
my $cgibin_path_to_photos = "../pics/$photo_directory";
my $web_path_to_photos = "pics/$photo_directory";

my $filename = '';
my $files = '';

# Get the list of the images to display
my @dir_contents = '';
my $work_dir = $curr_dir."$cgibin_path_to_photos";

opendir(DIR,$work_dir) || die("Cannot open directory !\n");
@dir_contents = sort readdir(DIR);
closedir(DIR);

# Format the images as clickable links
foreach $filename (@dir_contents) {
if (lc($filename) =~ /\.jpg/) {
  my $shortname = $filename;
    $shortname =~ s/\.jpg//;
    $shortname =~ s/\.JPG//;
    $files = "$files
      <a href=\"$web_path_to_photos/$filename\"><img src=\"$web_path_to_photos/$filename\" width=\"100\"
        border=\"0\" hspace=\"10\" vspace=\"10\" align=\"top\" /></a>";
  }
}

print header();
print "
<table width=\"100%\">
  <tr>
    <td width=\"3%\"></td>
    <td width=\"95%\">$files</td>
    <td width=\"2%\"></td>
  </tr>
</table>";