#!/usr/bin/perl -w

# $Id$

use strict;
use File::Basename;
use utf8;

# --------------------------------------------------------------------------------------------------
# Description: A simple exif template output generator
# Author:      Urs Stotz <stotz@typedef.ch>
# Year:        2011
# SVN public:  http://typedef.ch/svn/stotz/public/exif_template_generator/exif_template_generator.pl
# --------------------------------------------------------------------------------------------------

my $exiftool_url = 'http://www.sno.phy.queensu.ca/~phil/exiftool';

my $usage = "usage: exif_template_generator.pl <-h|--help|-?> | <parameters,...> [options,...]\n"
          . "  -h|--help|-?                this help\n\n"
          . "parameters:\n"
          . "  -image(s)=<filepattern>     the image file pattern\n"
          . "  -template=<templatefile>    the template file\n"
          . "  -output=<outputfile>        the output file\n\n"
          . "options:\n"
          . "  -exiftool=<exiftool>        the path to the exiftool (default: exiftool)\n"
          . "  -exif_tag=<-TAG>            the tag from where the exif data should be extracted (default -Description)\n"
          . "  -convert_to_ascii           try this parameter if you get some rubbish characters in your output file\n"
          . "  -code_injection=<perlcode>  code injection. The following example remove . at the end of a line from the variable \$exif_data:\n"
          . "     -code_injection='\$exif_data =~ s/\.\$//;'\n"
          . "  -TAG=<SEARCH_TAG>:<VALUE>   search this tag: <SEARCH_TAG> in the template file and replace it with <VALUE>.";

my $help = "template file example outdoorseiten.tmpl:\n"
          . "__HEAD__\n"
          . "Some text on the head of the page.\n"
          . "__IMAGES__\n"
          . "__EXIF_DESCRIPTION__:\n"
          . '[URL="__URL__/content/__FILE_BASE_NAME___large.html"][IMG]__IMG__/content/images/large/__FILE_BASE_NAME__.__FILE_SUFFIX__[/IMG][/URL]' . "\n"
          . "__FOOTER__\n"
          . "Some text on the footer of the page.\n\n"
          . "commandline example (on one line on Windows without backslash \\):\n"
          . "  exif_template_generator.pl -image=content/images/large/*.jpg \\\n"
          . "    -convert_to_ascii \\\n"
          . "    -template=outdoorseiten.tmpl \\\n"
          . "    -outputfile=outdoorseiten.txt \\\n"
          . "    -TAG=__URL__:http://typedef.ch/Outdoor/Bilder/20110213_Kaffee_direkt_in_einer_Tasse_bruehen \\\n"
          . "    -TAG=__IMG__:http://typedef.ch/Outdoor/Bilder/20110213_Kaffee_direkt_in_einer_Tasse_bruehen/300 \\\n"
          . "    -code_injection='\$exif_data =~ s/\.\$//;'\n\n"
          . "depends on exiftool: $exiftool_url\n\n"
          . "Author: Urs Stotz <stotz\@typedef.ch> Olten 2011";


sub exiftool;

my %parameter = ( exiftool => 'exiftool',
                  exif_tag => '-Description'
                );
eval {
  die("need parameter\n$usage\n") if (!@ARGV);
  while (my $arg = shift(@ARGV)) {
    if ($arg =~ m/^(?:-{0,2}help|-h|[\/-]{0,1}\?)$/) {
      print("$usage\n\n");
      print("$help\n");
      exit(0);
    }
    elsif ($arg =~ m/^-images{0,1}=(.+)$/) {
      $parameter{image} = $1;
    }
    elsif ($arg =~ m/^-exiftool=(.+)$/) {
      $parameter{exiftool} = $1;
    }
    elsif ($arg =~ m/^-convert_to_ascii$/) {
      $parameter{convert_to_ascii} = 1;
    }
    elsif ($arg =~ m/^-exif_tag=(.+)$/) {
      $parameter{exif_tag} = $1;
    }
    elsif ($arg =~ m/^-template=(.+)$/) {
      print("template $1\n");
      $parameter{template} = $1;
    }
    elsif ($arg =~ m/^-code_injection=(.+)/) {
      $parameter{code_injection} = $1;
    }
    elsif ($arg =~ m/^-outputfile=(.+)$/) {
      $parameter{outputfile} = $1;
    }
    elsif ($arg =~ m/^-TAG=([^:.]+):(.+)/) {
      $parameter{"-$1"} = $2;
    }
    else {
      die("unknown program parameter: $arg\n\n$usage\n");
    }
  }
  my %template;
  my $template_key = '__IMAGES__';
  print("read template: $parameter{template}\n");
  open(TEMPLATE, '<', $parameter{template}) || die("Can't open template file $parameter{template}: $!\n");
  LINE: while (<TEMPLATE>) {
    if (/^__HEAD__$/) {
      $template_key = '__HEAD__';
      next LINE;
    }
    if (/^__IMAGES__$/) {
      $template_key = '__IMAGES__';
      next LINE;
    }
    if (/^__FOOTER__$/) {
      $template_key = '__FOOTER__';
      next LINE;
    }
    $template{$template_key} .= $_;
    foreach my $key (keys %parameter) {
      if ($key =~ m/^-(.+)/) {
        my $search = $1;
        my $replace = $parameter{$key};
        $template{$template_key} =~ s/$1/$parameter{$key}/mg;
      }
    }
  }
  close(TEMPLATE);
  open(OUT, '>', $parameter{outputfile}) || die("Can't open outputfile $parameter{outputfile}: $!\n");
  my ($output, $exif_data);
  if (exists($template{__HEAD__})) {
    $output = $template{__HEAD__};
  }
  for my $file (glob($parameter{image})) {
    print("read exif data from file: $file\n");
    $exif_data = exiftool($file);
    my($filename, $directory, $suffix) = File::Basename::fileparse($file, qr/\.[^.]*/);
    $suffix =~ s/\.//;
    if (exists($parameter{code_injection})) {
      eval($parameter{code_injection});
    }
    $output .= $template{__IMAGES__};
    $output =~ s/__DIRECTORY__/$directory/mg;
    $output =~ s/__FILE_BASE_NAME__/$filename/mg;
    $output =~ s/__FILE_SUFFIX__/$suffix/mg;
    $output =~ s/__EXIF_DESCRIPTION__/$exif_data/mg;
  }
  if (exists($template{__FOOTER__})) {
    $output .= $template{__FOOTER__};
  }
  if (exists($parameter{convert_to_ascii})) {
    print("convert_to_ascii\n");
    utf8::decode($output);
  }
  print("write outputfile: $parameter{outputfile}\n");
  print(OUT $output);
  close(OUT);
};
if ($@) {
  print(STDERR "error: $@");
  exit(1);
}
exit(0);

sub exiftool
{
  my $file = shift;
  my $exif_data;
  die("$file is not a file\n$usage") if (! -f $file);
  open(EXIF, "$parameter{exiftool} $parameter{exif_tag} $file|")
    || die("error while open image: $file with $parameter{exiftool}\nperhaps you need exiftool form $exiftool_url\nerror: $!\n");
  while (<EXIF>) {
    ($exif_data) = (m/^.+\s*:\s*(.+)/m);
    chomp($exif_data);
  }
  close(EXIF);
  utf8::decode($exif_data);
  return $exif_data;
}

__END__

Copyright 2011 Urs Stotz <stotz@typedef.ch>. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice, this list of
      conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright notice, this list
      of conditions and the following disclaimer in the documentation and/or other materials
      provided with the distribution.

THIS SOFTWARE IS PROVIDED BY URS STOTZ ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those of the
authors and should not be interpreted as representing official policies, either expressed
or implied, of Urs Stotz.
