#!/bin/sh
set -eu


usage() {
	cat <<-'EOF'
		Usage:
		  re 'REGEXP' [FILE...]
		  re -h
	EOF
}

help() {
	cat <<-'EOF'


		Options:
		  -h, --help    show this message

		  REGEXP        the regular expresion to match and replace


		Execute a find and replace on files in a repository when
		no FILE... is given, listing them via "vcs ls" from vcs(1), or
		on the given FILE... list.

		EXPRESSION is to be forwarded to sed(1) directly.


		Examples:

		  Replace "weak" with "week" on the whole repository:

		    $ re 's/weak/week/g'


		  Delete lines beginning with "import" on package.py:

		    $ re '/^import/d' package.py
	EOF
}


for flag in "$@"; do
	case "$flag" in
		(--)
			break
			;;
		(--help)
			usage
			help
			exit
			;;
		(*)
			;;
	esac
done

while getopts 'h' flag; do
	case "$flag" in
		(h)
			usage
			help
			exit
			;;
		(*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))

REGEXP="${1:-}"
eval "$(assert-arg -- "$REGEXP" 'REGEXP')"
shift


replace() {
	FILE="$1"
	# shellcheck disable=2094
	if ! sed -E "$REGEXP" < "$FILE" | cmp -s - "$FILE"; then
		if [ ! -e "$FILE" ]; then
			return 1
		fi
		sed -E "$REGEXP" < "$FILE" | sponge "$FILE"
	fi
}

if [ -n "${1:-}" ]; then
	for f in "$@"; do
		replace "$f"
	done
else
	vcs ls | while read -r f; do
		replace "$f"
	done
fi
