#!/usr/bin/env bash
# Generate compatible patch files for pkgcruft tests.
#
# Usage: Modify files under a given directory and then run this script in the
# directory. Note that `git clean -fxd` is run automatically and the generated
# patch file is staged.

set -e

TARGET_DIR=${PWD/*\//}
cd ..
cp -av "${TARGET_DIR}" "${TARGET_DIR}".new >/dev/null
git checkout "${TARGET_DIR}" &>/dev/null
mv "${TARGET_DIR}" "${TARGET_DIR}".orig
mv "${TARGET_DIR}".new "${TARGET_DIR}"

# generate patch file
FILE=$(mktemp -p .)
diff -x fix.patch -Naur "${TARGET_DIR}".orig "${TARGET_DIR}" > "${FILE}" || true

mv "${TARGET_DIR}" "${TARGET_DIR}".old
mv "${TARGET_DIR}".orig "${TARGET_DIR}"

# verify patch with content was created
if [[ -s ${FILE} ]]; then
	# move file to expected location
	mv "${FILE}" "${TARGET_DIR}"/fix.patch
	git add "${TARGET_DIR}"/fix.patch
else
	rm ${FILE}
	echo no changes detected under current directory
fi

git clean -fxd >/dev/null
cd "${TARGET_DIR}"
