#!/usr/bin/env bash

set -euo pipefail

usage() {
	cat <<'EOF'
Usage: icloud.sh [--apply] [directory]

Recursively finds files and folders whose names contain " 2" or " 3".
By default it only prints what would be deleted.

Options:
	--apply; Actually delete the matched paths.
	--help; Show this help text.

Examples:
	./icloud.sh
	./icloud.sh ~/Documents
	./icloud.sh --apply .
EOF
}

apply=false
target_dir="."

while [[ $# -gt 0 ]]; do
	case "$1" in
		--apply)
			apply=true
			shift
			;;
		--help|-h)
			usage
			exit 0
			;;
		*)
			target_dir="$1"
			shift
			;;
	esac
done

if [[ ! -d "$target_dir" ]]; then
	echo "error: not a directory: $target_dir" >&2
	exit 1
fi

matches=()
while IFS= read -r -d '' path; do
	matches+=("$path")
done < <(find "$target_dir" -mindepth 1 -depth \( -name '* 2*' -o -name '* 3*' \) -print0)

if [[ ${#matches[@]} -eq 0 ]]; then
	echo "No matching files or folders found in: $target_dir"
	exit 0
fi

if [[ "$apply" == false ]]; then
	echo "Matching paths:"
	for path in "${matches[@]}"; do
		printf '  %q\n' "$path"
	done
	echo
	echo "Run with --apply to delete these ${#matches[@]} path(s)."
	exit 0
fi

echo "Deleting ${#matches[@]} path(s) from: $target_dir"
for path in "${matches[@]}"; do
	printf 'Deleting %q\n' "$path"
	rm -rf -- "$path"
done
