# annotate - executes a program annotating the output linewise with time and stream
#
# ---
# see: https://jeroen.a-eskwadraat.nl/sw/annotate/annotate

addtime() {
  while read -r line; do
    echo "$(date "+%H:%M:%S") $1: ${line}"
  done
}

OUT=$(mktemp /tmp/annotate.XXXXXX) || exit 1
ERR=$(mktemp /tmp/annotate.XXXXXX) || exit 1

rm -f "${OUT}" "${ERR}"
mkfifo "${OUT}" "${ERR}" || exit 1

addtime O <"${OUT}" &
addtime E <"${ERR}" &

echo "$(date "+%H:%M:%S") I: Started $*"
"$@" >"${OUT}" 2>"${ERR}"
EXIT=$?
rm -f "${OUT}" "${ERR}"
wait

echo "$(date "+%H:%M:%S") I: Finished with exitcode ${EXIT}"

exit "${EXIT}"
