#!/usr/bin/env zsh

if [[ -n "$1" ]]; then
  cd "$1"
fi

dir="${1:-.}"
album=album.xml

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

<thumbnail> %SAMPLE% </thumbnail>

<date> %DATE% </date>
<order> %ORDER% </order>

<shortdesc>
%SHORT%
</shortdesc>

<longdesc>

%LONG%

</longdesc>

</config>
'
offset=11

if [[ -e "$album" ]]; then
  echo "Album already exists; editing ..."
  $VISUAL +$offset "$album"
  exit 0
fi

read 'title?Album title? '
read 'date?Date? '
read 'short?Short description for album index? '
read 'long?Longer description for within album? '
read 'order?Ordering number? '

# zsh needs a do ... until
read 'sample?Sample image [blank for random] ? '

while [[ -n "$sample" && ! -e "$sample" ]]; do
  echo "$sample doesn't exist in $dir; please choose from one of the following:"
  ls *(.)
  read 'sample?Sample image [blank for random] ? '
done

local template="$image_xml_template"
template=${template:s/%TITLE%/$title}
template=${template:s/%DATE%/$date}
template=${template:s/%SHORT%/$short}
template=${template:s/%LONG%/$long}
template=${template:s/%SAMPLE%/$sample}
template=${template:s/%ORDER%/$order}
echo "$template" > "$album"

if read -q '?Edit album file [y/N] ? '; then
  $VISUAL +$offset "$album"
fi

