#!/usr/local/bin/bash
#
# $Id: imgconvert,v 1.44 2024/11/22 02:49:05 grog Exp $
# Convert image files based on Makejpeg file entries.
# Called from convert with the parameters for a single image.
# This script tries multiple name extensions in sequence:
EXTENSIONS="_DxO.tif _DxO.tiff _DxO.jpg .jpeg .jpg .JPEG .JPG .gif .GIF .png .PNG .tiff .tif"

echo $0 $*
# Usage:
# imgconvert [-l]  infile outfile Exif-spcs
# -l means "link, don't convert"
# XXX -l could be a chop candidate.
# The rest of the parameters are a line from Makejpeg:
#   infile  outfile createexif parms
#   infile is implicitly in orig/
if [ "$1" = "-l" ]; then
  LINK=1
  shift
else
  LINK=0
fi
SOURCE=orig/$1			# source file implicitly in orig/
NAME=$2
HAVEEXIFPARMS=$4		# We have parameters for createexif
ECHO=
# Debug
# ECHO=echo
QUALITY=75%			# for JPEG conversions
if [ "$AUTHOR" = "" ]; then
  AUTHOR="Greg Lehey"
fi
DIR=orig
# What a pain these extensions are
# What we want to do:
# - If the exact file name exists in orig/, use it.
# - Otherwise strip any extensions and try again with every extension
#   we know.
FOUND=yes
if [ ! -e $SOURCE ]; then
  FOUND=
#  echo Finding $SOURCE
  for i in $EXTENSIONS; do
    SOURCE=${SOURCE/$i/}
  done
#  echo Base: $SOURCE
  for i in $EXTENSIONS; do
    if [ -f $SOURCE$i ]; then
      SOURCE=$SOURCE$i
      FOUND=yes
      break
    fi
  done
fi
# in case we have crap at the end of the destination name, this will
# remove it.
# In revision 1.39 I wrote:
#    XXX this removes any extension specifications for the destination
#        file.  That might once have made sense, but I don't think it
#        does any more.  In particular I may want to convert from PNG to
#        JPEG.
# But I no longer know why, and it broke other things.
for i in $EXTENSIONS; do
   NAME=${NAME/$i/}
done
if [ "$FOUND" = "" ]; then
  echo No conversion candidate found to convert $SOURCE to $NAME
  exit 1
fi
echo ---- Looking at $SOURCE
# Take first line only in case there are thumbnails
TYPE=`identify $SOURCE 2>/dev/null | head -n 1 | awk '{print $2}'`
# XXX FIX this!
if [ $TYPE = "GIF" ]; then
  NAME=$NAME.gif
elif [ $TYPE = "PNG" ]; then
# We don't want PNG files on the web
  NAME=$NAME.jpeg
  CONVERT=T
elif [ "$TYPE" = "TIFF" ]; then
  NAME=$NAME.tiff
else    # We convert everything else to JPEG, notably TIFFs.
    NAME=$NAME.jpeg
fi
if [ ! -s $NAME -o \( $NAME -ot $SOURCE \) ]; then
  echo converting $SOURCE to $NAME
  rm -f PC/$NAME # we'll need to re-optimize
  if [ "$CONVERT" = "T" ]; then	# probably a PNG conversion,
    convert -quality $QUALITY $SOURCE $NAME
  else
    ln $SOURCE $NAME
  fi
  if [ -f orig/gpslog ]; then	# add GPS information if available
    $ECHO geotag $NAME
  fi
  $ECHO touch -r $SOURCE $NAME	# reinstate modification time stamp
fi
