#! /bin/bash -eu
# Last edited on 2025-12-22 09:38:23 by stolfi

this_script="$0"
idir="$1"; shift    # Folder with the annotated script.

pdir="${HOME}/programs/bash/js_image_tools"
prog="${pdir}/annotate_image.sh"
paux="${pdir}/make_annotate_image_commands.py"

echo "idir = ${idir}" 1>&2
ofile="${idir}/annotated.png"

annot_script="annotate.sh"
if [[ -x ${idir}/${annot_script} ]]; then
  if [[ \
    (! -s ${ofile} ) || \
    ${idir}/${annot_script} -nt ${ofile} || \
    ${this_script} -nt ${ofile} || \
    ${prog} -nt ${ofile} || \
    ${paux} -nt ${ofile} \
  ]]; then

    # Clean slate:
    rm -fv ${ofile}

    # Estract and annotate the clipped image:
    hdir="${PWD}"
    ( cd ${idir} && export PATH="${hdir}:${PATH}"; ${annot_script} )

    if [[ -s ${ofile} ]]; then
      # Display it:
      title="`echo $PWD | sed -e 's:^.*/report/::g'`"
      display -title "${title}" ${ofile}
      # gimp -n -s ${ofile}

      # Export for VoynichNinja:
      jname="`echo $PWD | sed -e 's:^.*/Notes/::g' -e 's:/:-:g'`"
      echo "jname = ${jname}" 1>&2

      jsect="${jname/-*}"
      echo "jsect = ${jsect}" 1>&2

      jdir="${HOME}/projects/voynich/VoynichNinja/${jsect}"
      echo "jdir = ${jdir}" 1>&2
      mkdir -p ${jdir}
      # VoynichNinja wants all uploads to have different names, so:
      jfile="${jdir}/${jname}.jpg"
      echo "jfile = ${jfile}" 1>&2
      convert ${ofile} ${jfile}
      ls -ld ${ofile} ${jfile}
    else
      echo "** file ${ofile} not created" 1>&2;
    fi
  else
    echo "!! file ${ofile} seems up-to-date"
  fi
else
  echo "** no executable file ${idir}/${annot_script}" 1>&2;
fi
