#! /bin/bash
# Last edited on 2023-09-01 21:56:03 by stolfi

# Determines if a derived file needs to be recomputed from its sources.
# Sort of like {make}.
# 
# Expects to be given the names of the derived file {OUT_FILE} and of
# zero or more source files {IN_FILE[0] IN_FILE[1] ..} . 
# 
# Writes "1" to standard output if {OUT_FILE} is missing, empty, or is older
# than any source file
# 
# Writes "0" if {OUT_FILE} is present and newer than all of them.
# 
# In any case, fails with error message if any of the source files is missing
# or empty.

OUT_FILE="$1"; shift

# ls -l ${OUT_FILE}

# Must redo ${OUT_FILE} if it is missing or empty:
if [[ ! ( -s ${OUT_FILE} ) ]]; then
  echo "file ${OUT_FILE} is missing or empty" 1>&2
  redo=1
else
  redo=0
fi

# Check existence of the source files in any case:
for IN_FILE in "$@" ; do 
  if [[ ! ( -s ${IN_FILE} ) ]]; then 
    echo "** ${IN_FILE} is missing or empty" 1>&2; exit 1 
  elif [[ ( -s ${OUT_FILE} ) && ( ${IN_FILE} -nt ${OUT_FILE} ) ]]; then
    echo "file ${IN_FILE} is newer than ${OUT_FILE}" 1>&2 
    redo=1
  fi
done
echo ${redo}

