#!/bin/sh -eu
# When invoked with an absolute path name as an argument, redo-whichdo
# must output non-existent dofiles in the parent directory and the
# same directory until it outputs one that exists.

if ! test -d a; then
 mkdir a
fi

dofiles="default.do default.c.do default.b.c.do a/default.do a/default.c.do a/default.b.c.do a/a.b.c.do"

for dofile in ${dofiles}; do
 if test -e "${dofile}"; then
  rm -- "${dofile}"
 fi
done

for dofile in ${dofiles}; do
 >"${dofile}" cat <<EOF
printf '${dofile}\n'
EOF

 whichdo_dofiles=$(
  redo-whichdo "${PWD}/a.b.c" \
   |tr '\0' '\n'
 )

 whichdo_dofiles_nonexistent=$(
  printf '%s\n' "${whichdo_dofiles}" \
   |sed '$d'  # BusyBox v.1.19.3 has no “head -n-1”
 )
 for whichdo_dofile_nonexistent in ${whichdo_dofiles_nonexistent}; do
  if test -e "${whichdo_dofile_nonexistent}"; then
   >&2 printf 'redo-whichdo prints %s as nonexistent dofile, but it exists.\n' \
    "${whichdo_dofile_nonexistent}"
   exit 1
  fi
 done

 whichdo_dofile_existent=$(
  printf '%s\n' "${whichdo_dofiles}" \
   |tail -n1
 )
 if ! test -e "${whichdo_dofile_existent}"; then
  >&2 printf 'redo-whichdo prints %s as existent dofile, but it does not exist.\n' \
   "${whichdo_dofile_existent}"
  exit 1
 fi

done
