#!/usr/bin/env bash

if [ -z "${TMPDIR}" ]; then
  tmpdir_infix="yandl"
  tmpdir_root="/tmp"
  tmpdir_prefix="tmp.__omw-"
  tmpdir_pattern="${tmpdir_prefix}${tmpdir_infix}-XXXXXXXXXX"
  fd -t d --changed-before 1h "${tmpdir_prefix}" "${tmpdir_root}" -x rm -r {}
  TMPDIR="$(mktemp --directory --tmpdir=${tmpdir_root} "${tmpdir_pattern}")"
  export TMPDIR
fi

main() {
tlog="$(mktemp)"
if [ -d "01 Modular" ]; then rm -r "01 Modular"; fi
if [ -d "02 Merged" ]; then rm -r "02 Merged"; fi
./01_yandl_modular.sh 2>&1 | tee -a "${tlog}"
./02_yandl_merged.sh 2>&1 | tee -a "${tlog}"

if rg -i 'error|warning|not modified' "${tlog}"; then
  echo "error"
  return 1
fi

printf '\n\n\tCOMPARE AND MOVE:\n\n'
# shellcheck disable=SC2016
fd . -t f "4/01 Modular" -x sh -c 'if ! diff -q "${0}" "${0#*/}" >/dev/null 2>&1; then cp -v "${0#*/}" "${0}"; fi' "{}"
# shellcheck disable=SC2016
fd . -t f "4/02 Merged" -x sh -c 'if ! diff -q "${0}" "${0#*/}" >/dev/null 2>&1; then cp -v "${0#*/}" "${0}"; fi' "{}"
}
main "$@" || { echo "error"; exit 1; }
