#!/usr/bin/env zsh

setopt extendedglob

if [[ -z "$@" ]]; then
  cd ~/images/incoming
  photos=( (STA|IMG)_*.JPG(N) )
else
  photos=( "$@" )
fi

if (( $#photos == 0 )); then
  echo "No unclassified photos found; aborting."
  exit 1
fi

image_xml_template='<?xml version="1.0" ?>
<photo>
<title> %TITLE% </title>

<description>

%LONGDESC%

</description>

<date> %DATE% </date>

<order> %ORDER% </order>
<event> </event>
<location> </location>
<people> </people>
</photo>
'
offset=7

typeset -A times

get_index () {
  echo -n "Ensure camera is connected and on, then press any key... "
  read -k
  ixus -L >INDEX
}

if [[ -e INDEX ]]; then
  if read -q '?INDEX file already exists.  Update [y/N] ? '; then
    get_index
  fi
  eval "times=( $( ~/perl/photos/INDEX2assoc.pl INDEX ) )"
else
  echo "INDEX file not found (needed for date/time)."
  if read -q '?Generate one now [y/N] ? '; then
    get_index
  else
    echo "No INDEX file available, <date> field will be left empty."
  fi
fi

foreach photo in $photos; do
  gqview -t $photo >&/dev/null &!

  echo

  if [[ -z "$times[$photo]" ]]; then
    cat <<EOF
Warning!  Couldn't figure out a timestamp for this one.  Please either
^C now and rebuild INDEX, or enter a timestamp manually (defaults to now).
The mtime of the file is listed below:
EOF
    ls -l $photo
    read 'manualtime?> '
    times[$photo]=${manualtime-`date`}
  else
    echo "Got time for $photo: $times[$photo]"
  fi

  read "newname?New name for $photo (blank to skip, or OLD) ? "
  if [[ -z "$newname" ]]; then
    echo "Skipping this image."
    continue
  fi

  if [[ "$newname" == OLD ]]; then
    newname="$photo"
  fi

  if [[ -e "$newname.xml" ]]; then
    echo "xml file already existed; editing ..."
    $VISUAL +$offset "$newname.xml"
    continue
  fi

  ext=${photo:e:l}
  newfilename="${${newname// /_}:r}.$ext"

  newname_no_digits="${newname/#[0-9]## #/}"
  read "title?Short title [${newname_no_digits}] ? "
  : ${title:=$newname_no_digits}

  read 'longdesc?Longer description [] ? '
  read 'order?Ordering number [] ? '

  local template="$image_xml_template"
  template=${template:s/%TITLE%/$title}
  template=${template:s/%LONGDESC%/$longdesc}
  template=${template:s/%DATE%/$times[$photo]}
  template=${template:s/%ORDER%/$order}
  echo "$template" > $newfilename.xml

  if [[ "$photo" != "$newfilename" ]]; then
    echo Renaming $photo to $newfilename ...
    mv -i $photo $newfilename
  fi

  if read -q '?Edit info file for this photo [y/N] ? '; then
    $VISUAL +$offset $newfilename.xml
  fi
done

echo
if read -q '?Make album for current directory [y/N] ? '; then
  make-album
fi
