#!/bin/sh
set -ef

# $1 - directory to search in
# $2 - misspelled text
# $3 - corrected text (may be empty)
[ -d "$1" ] ; [ -n "$2" ]

# "safe" sed separator
s=$(printf '\027')

env printf ' --- Fix spelling: %q -> %q\n' "$2" "$3" >&2

t=$(mktemp); : "${t:?}"
_cleanup() { rm -f -- "${t}"; exit ${1:-0}; }
trap '_cleanup $?' EXIT INT HUP ALRM TERM

grep -FZl -r -e "$2" "$1/" | sed -zE "s${s}^$1/${s}${s}g" | sort -zuV > "$t" || :

[ -s "$t" ] || {
	echo " --- The above fix is no longer necessary" >&2
	exit 0
}

echo ' --- Affected files:' >&2
xargs -a "$t" -0r printf '%s\n' </dev/null >&2
echo ' --- end of file list' >&2

env -C "$1" xargs -a "$t" -0r sed -i "s${s}$2${s}$3${s}g" </dev/null
exit 0
