#! /bin/bash -e

USAGE=( \
  "annotate_image.sh {-help|-info}\n"
  "annotate_image.sh [-debug] {SOURCE_IMG} {COMMAND}...\n"
)

debug=0
debug_opts=( )
while [[ ( $# -ge 1 ) && ( "/$1" =~ /- ) ]]; do
  if [[ ( "/$1" == "/-help" ) || ( "/$1" == "/--help" ) || \
      ( "/$1" == "/-info" ) || ( "/$1" == "/--info" ) ]]; then
    echo "USAGE: ${USAGE[@]}" 1>&2 
    ${HOME}/lib/make_annotate_image_commands.py -info
    exit 0
  elif [[ "/$1" == "/-debug" ]]; then
    debug=1; shift
    debug_opts=( -debug True )
  else
    echo "** invalid option '$1'" 1>&2;
    echo "USAGE: ${USAGE[@]}" 1>&2 
    exit 1
  fi
done

src="$1"; shift   # Source image

tmp="/tmp/$$"

# Get source image size:
size=( `convert ${src} -print "%[fx:w] %[fx:h]\n" null: `)
echo "image size = ${size[@]}" 1>&2 

echo "convert ${src} +repage -colorspace sRGB -alpha off \\" > ${tmp}.cmds

# TESTS:
# echo "  -fill black -draw 'circle 100,100 120,100' \\" >> ${tmp}.cmds
# echo "  -pointsize 20.0 -fill black -draw 'text 100,100 \"HELLO\"' \\" >> ${tmp}.cmds
# echo "  -filter Mitchell -draw 'text 100,200 \"HELLO\"' \\" >> ${tmp}.cmds

${HOME}/lib/make_annotate_image_commands.py \
    ${debug_opts[@]} \
    -imagesize ${size[@]} \
    "${@}" \
  >> ${tmp}.cmds

echo "  ${tmp}.png" >> ${tmp}.cmds

if [[ ${debug} -ne 0 ]]; then
  echo "draw commands:" 1>&2
  cat ${tmp}.cmds 1>&2
fi

source ${tmp}.cmds

# display ${tmp}.png

cat ${tmp}.png
rm ${tmp}.png ${tmp}.cmds
