#!/usr/local/bin/bash
# Create temporary web pages as "contact prints"
#
# Usage: $0 [-cm] [-m] [-r] [me]
#
#        -c means clean dest dir first
#        -m means "don't copy Makejpeg"
#        -r means "don't rotate", needed for embedded images.
#        me is the user name.
#
# Environment variable PHOTOS, if present, is a list of photos to generate.
# It defaults to *.JPG *.JPEG *.jpg
#
# Care: revision 1.34 of 6 October 2015 changes the semantics of the
# first column name.  Previously it assumed an implicit .jpg at the
# end.  Now it's the exact name.
#
# $Id: mkcontacts,v 1.51 2023/11/18 03:46:57 grog Exp $
#
if [ "$1" = "-c" ]; then
  CLEAN=yes
  shift
fi
if [ "$1" = "-m" ]; then
  MAKEJPEG=no
  shift
fi
if [ "$1" = "-r" ]; then
  ROTATE=no
  shift
fi
if [ "$1" != "" ]; then
  ME=$1
else
  ME=`whoami`
fi
if [ "$BY" = "" ]; then
  BY=36
fi
# The intention here is to create lines with the traditional 6 images
# at a size that fits on a full screen.  For 1920 pixel display,
# that's 270 pixels.  For a 2560 pixel wide screen, that's 400 pixels.
#
# Be cleverer about this one.  Currently the Makefile kludges it.
if [ "$WIDTH" = "" ]; then
  WIDTH=270
fi;
MYDIR=`pwd`
DIRDATE=`basename $MYDIR`
CONTACTS=/home/$ME/public_html/localtmp/contacts
TMPDIR=$CONTACTS/$DIRDATE
TOOLS=/home/grog/Photos/Tools
DIR=`pwd`
DATE=`basename $DIR`
PATHNAME=$DATE
# rm -rf $TMPDIR
ln -s $MYDIR/.. $CONTACTS/Rawphotos
mkdir -p $TMPDIR
chmod 777 $TMPDIR   # to allow web server to write here
if [ "$CLEAN" = "yes" ]; then
  rm -f $TMPDIR/*
fi
pwd
if [ "$MAKEJPEG" != "no" ]; then
  if [ -f Makejpeg ]; then
    if [ ! -f $TMPDIR/Makejpeg -o Makejpeg -nt  $TMPDIR/Makejpeg ]; then
      rm -f $TMPDIR/Makejpeg
      cp -p Makejpeg $TMPDIR
    fi
  elif [ -f makejpeg ]; then
    if [ ! -f $TMPDIR/Makejpeg -o Makejpeg -nt  $TMPDIR/Makejpeg ]; then
      rm -f $TMPDIR/Makejpeg
      if [ -f description ]; then
        cat description > $TMPDIR/Makejpeg
      else
        echo > $TMPDIR/Makejpeg
      fi
      cat makejpeg >> $TMPDIR/Makejpeg
    fi
  fi
  chmod 666 $TMPDIR/Makejpeg
fi
# XXX
if [ -d orig ]; then
  cd orig
  PATHNAME=$DATE/orig
fi
# We only want one kind of JPEG image.  Over the years I've used
# different spellings of the extension for different meanings.  The
# ones that remain are .JPG (out of camera) and .jpg (preprocessed,
# typically by DxO.  .jpg has priority over .JPG.  I have a vague
# recollection that .JPEG and .jpeg were outputs of other processors,
# so I'm assinging the priority .jpg, .jpeg, .JPEG and .JPG.  The
# first wins.
#
if [ "$PHOTOS" = "" ]; then
  for i in `ls -rt *.jpg *.JPG *.gif *.tiff *.tif *.png *.PNG *.MOV .mp4 2>/dev/null`; do
    PHOTOS="$PHOTOS $i"
  done
fi
# XXX echo DIR `pwd` PHOTOS $PHOTOS
WEBPAGE=index.php
THISPAGE=$TMPDIR/$WEBPAGE
# XXX echo MYDIR $MYDIR DIRDATE $DIRDATE TMPDIR $TMPDIR THISPAGE $THISPAGE
cat > $THISPAGE << EOF
<!-- for Emacs, this is a -*- html-fill; coding: utf-8 -*- document -->
<!-- \$Id: mkcontacts,v 1.51 2023/11/18 03:46:57 grog Exp $ -->
<!DOCTYPE HTML>
<?php
   include "header.php";
   include "docontacts.php";
   /* title should start with a lower case character */
   \$title = "contact prints";
   \$subtitle = printdate ("$DATE");
   \$id = '\$Id: mkcontacts,v 1.51 2023/11/18 03:46:57 grog Exp $';
   \$wantgroogle = 0;
   \$rightextras = "/$ME/photos/Photos.php?dirdate=$DATE Web page for " . printdate ("$DATE") ."\n"
                 . "Makejpeg Current Makejpeg file\n"
                 . ".. Contact print index\n"
                 . "/$ME/localtmp/compare/compare.php Optimization comparison\n";
 ?>

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <?php pagetitle (\$title); ?>
    <!-- Fix this! -->
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <script type="text/javascript" src="/grog/js/tipmessage/main.js"></script>
  </head>

  <body>
  <div id="TipLayer" style="visibility:hidden;position:absolute;z-index:1000;"></div>
    <script type="text/javascript">
      Style = ["white",
               "black",
               "#000099",
               "#E8E8FF",
               "",
               "",
               "",
               "",
               "",
               "",
               "",
               "2",   /* StickyStyle */
               "",
               "",
               500,  /* Width, in pixels */
               "",
               2,
               2,
               100,
               50,
               51,
               1,
               0,
               "",
               ""]
    </script>
    <?php
      pageheader (\$title);
      \$descfile = "makejpeg";
      if (file_exists (\$descfile))
        \$descr = file_get_contents (\$descfile);
      else
        \$descr = "";
      \$description = "";       /* XXX fix this */
    ?>
    <div align="left">
EOF
echo -n >> $THISPAGE "    <?php \$imagelist = \""
for i in $PHOTOS; do
  # Handle video clips
  BASE=`basename $i .MOV`
  BASE=`basename $BASE .mp4`
  if [ $BASE != $i ]; then    # there must be a better way to do this
    MPG=$TMPDIR/$BASE.mpg
    if [ ! -f $MPG ] ; then
      ln -f -s `pwd`/$i $MPG
     convert 2> /dev/null -geometry $WIDTH $i[24] $TMPDIR/$BASE.jpeg
    fi
    echo -n "$i " >> $THISPAGE
  else				# still image
    EXIFFILE=$i
    for J in .JPG .jpg .JPEG .jpeg _DxO.jpg; do
      EXIFFILE=`basename $EXIFFILE $J`
    done
    EXIFFILE=$TMPDIR/$EXIFFILE.exif
    if [ ! -f $EXIFFILE ]; then
      nice -5 mkexif2 $i $TMPDIR
    fi
    if [ "$ROTATE" = "no" ]; then
        ROTATION=
    else
        ROTATION=`grep "Orientation" $EXIFFILE | awk '{print $4}'`
    fi
    CONTACT=$TMPDIR/${i/.embedded/}
    FOO=${CONTACT/tiff/jpg}  # web browsers can't display TIFF
    FOO=${FOO/tif/jpg}  # and again for castrated file names
    if [ "$FOO" != "$CONTACT" ]; then
	# We have a TIFF file.  Is there also a JPEG file?
	BAZ=`basename $FOO`
	BAR=${BAZ/jpg/jpeg}
# XXX echo > /dev/tty === `pwd` Checking  for $BAZ or $BAR
      if [ -f $BAZ -o -f $BAR ]; then
	echo > /dev/tty $BAZ or `basename $BAR` exists, skipping $CONTACT
	continue
      else
	echo > /dev/tty Creating $CONTACT \($BAZ\)
      fi
      ISTIFF=1
    else
      ISTIFF=0
    fi
    CONTACT=$FOO
# XXX compare ctimes.
    if [ -f $CONTACT ]; then
      CCTIME=`ls -lcD"%s" $CONTACT | awk '{print  $6}'`
      ICTIME=`ls -lcD"%s" $i | awk '{print  $6}'`
      if [ $CCTIME -gt $ICTIME ]; then
	DOIT=
	echo > /dev/tty Comparing $CONTACT and $i, no doit
      else
        DOIT=YES
	CCDATE=`date -j -r $CCTIME`
	ICDATE=`date -j -r $ICTIME`
	echo > /dev/tty Comparing $CONTACT and $i, doit \($CCTIME \> $ICTIME\, $CCDATE \> $ICDATE\)
      fi
    else
      DOIT=YES
    fi
#    echo $CONTACT $CCTIME $ICTIME $DOIT > /dev/tty
    if [ $DOIT ]; then
        # DxO generates lots of erroneous fields and data types.
#	identify $i > /dev/tty
        SIZE=`identify $i 2>/dev/null | head -n 1 | awk '{print $3}'`
        HORIZ=`echo $SIZE | sed 's:x.*::'`
        VERT=`echo $SIZE | sed 's:.*x::'`
        if [ "$HORIZ" -gt "$VERT" ]; then
            GEOMETRY=$WIDTH
        else
            GEOMETRY=x$WIDTH
        fi
#	echo SIZE $SIZE geometry $GEOMETRY > /dev/tty XXX
        echo Converting $i to $CONTACT > /dev/tty
      # This echo is the only thing that goes to stdout, where it's piped
      # into "by".
      if [ "$ROTATION" = "" -o "$ROTATION" = "(normal)" ]; then
        ROTATED=
        if [ $ISTIFF -eq 1 ]; then
          # The TIFFs contain two images.   We take the first, and reinstate the EXIF data.
#          echo >/dev/tty `pwd`:  XXX "nice -5 convert 2> /dev/null -geometry $GEOMETRY $i[0] $CONTACT && exifcopy $i $CONTACT"
          echo "nice -5 2> /dev/null convert -geometry $GEOMETRY $i[0] $CONTACT && exifcopy $i $CONTACT"
        else
#          echo > /dev/tty "`pwd` nice -5 convert 2> /dev/null -geometry $GEOMETRY $i $CONTACT"
          echo "nice -5 convert 2> /dev/null -geometry $GEOMETRY $i $CONTACT"
        fi
      else			# requires rotation
        ROTATED="(rotated $ROTATION°)"
        if [ $ISTIFF -eq 1 ]; then
          # convert drops the EXIF data for TIFFs.
          echo "nice -5 convert 2> /dev/null -rotate $ROTATION -geometry $GEOMETRY $i[0] $CONTACT"
	  echo "exifcopy $i $CONTACT"
        else
          echo "nice -5 convert 2> /dev/null -rotate $ROTATION -geometry $GEOMETRY $i $CONTACT"
        fi
      fi
    fi
    # This ends up in the $imagelist string.
  # XXX  echo -n "$i x $ROTATION y $ROTATE z $EXIFFILE " >> $THISPAGE
    echo -n "`basename $CONTACT` " >> $THISPAGE
  fi				# choice video/still
done | by $BY
cat >> $THISPAGE << EOF
";
      docontacts (\$description, $DIRDATE, \$imagelist); ?>
    </div>

<?php pagefooter (\$id, \$rightextras); ?>
EOF
