#!/usr/local/bin/bash
#
# Run Ashampoo photo optimizer
#
# $Id: photoopt,v 1.39 2020/03/18 01:42:15 grog Exp grog $
#
if [ "$BY" = "" ]; then
  BY=5
fi
if [ "$1" = "-r" ]; then
  RECOVER=yes
  shift
fi
if [ "$1" = "-a" ]; then	#  all JPEG files
  ALL=yes
  shift
fi
ABACKUP=_Ashampoo_Photo_Optimizer_Backup
if [ "$OPTDIR" = "" ]; then
  OPTDIR=/Photos/Ashampoo-`whoami`
fi
OLDDIR=`pwd`           # current (source) directory
if [ "$RECOVER" = "" ]; then    # start off
  # This is the new Ashampoo obfuscatory path to the copies of the
  # original images.
  rm -rf $OPTDIR/photoOptimizeHistoryDataBase
  if [ $# -gt 0 ]; then
    FILES=$*
  elif [ "$ALL" = "yes" -o ! -d $ABACKUP ]; then
    FILES=`ls *.jpeg *.png  *.tiff 2>/dev/null`  # all .jpeg and .png files
  else				# only non-optimized files
    FILES=
    for file in `ls *.jpeg *.png *.tiff 2>/dev/null`; do
# XXX FIXME We need a function to strip extensions
      BASE=`basename $file .jpeg`
#      echo $file
# echo looking for $ABACKUP/$file $ABACKUP/$BASE.tiff
      if [ ! -f $ABACKUP/$file -a ! -f $ABACKUP/$BASE.tiff ]; then
#      echo Adding $file
        FILES="$FILES $file"
      fi
    done
  fi
  if [ "$FILES" = "" ]; then
    espeak "No files to optimize"
    echo No files to optimize
    exit 1
  fi
  echo Optimizing `echo $FILES | wc -w` files: $FILES
  # Decided on our files, put them in the other dir
  rm -rf $OPTDIR/*
  mkdir $OPTDIR
  ln $FILES $OPTDIR
  cd $OPTDIR
  chmod g+w . *			# because Samba is too stupid
  espeak "Press Return when Ashampoo has done its thing"
  echo Press Return when Ashampoo has done its thing
  read toignore
else
  cd $OPTDIR
fi
# note that $ABACKUP is really $OPTDIR/$ABACKUP
# Hidden backup directory
echo Looking in `pwd`//$OPTDIR
FILES=
for HIDDEN in $OPTDIR/*photoOptimize*/*/*; do
  FILES="$FILES `cd $HIDDEN && ls 2> /dev/null`"
  echo FILES \"$FILES\"
done
if [ "$FILES" = "" ]; then
  espeak "No photos optimized  $ABACKUP"
  echo No photos optimized  $ABACKUP
  exit 0
fi
# reinstate the time stamps and EXIF info
mkdir -p $OLDDIR/$ABACKUP	# in case this is the first time
cd $HIDDEN && cp -p $FILES $OLDDIR/$ABACKUP
echo Moving `pwd` to $OLDDIR/$ABACKUP
# Not sure what Ashampoo uses these for, but we don't.
rm $OLDDIR/$ABACKUP/*jpeg.d.jpeg $OLDDIR/$ABACKUP/_sourceID
cd $OLDDIR
espeak "Comparing files"
echo Comparing for $FILES
sleep 1         # give a chance to ^C.
echo ${PHOTOTOOLS}/mkcompare $FILES
${PHOTOTOOLS}/mkcompare $FILES
espeak "Done!"
