#!/bin/bash

set -eu -o pipefail

top_dir="$(readlink -m "${BASH_SOURCE[0]}/../..")"

# Also allow operation on a copy named ${orig_top_dir}.clean-check.${something}
# I.e., .../graphene.clean-check.test/Scripts/clean-check will check:
# .../graphene.clean-check.test against .../graphene.clean-check.clean
clean_dir="${top_dir%.clean-check.*}.clean-check.clean"

if [ -n "${JENKINS_HOME:-}" ]; then
    clean_dir="/tmp/$(basename "$clean_dir")"
fi

show_diff=false
if [ "${1:-}" == "--show-diff" ]; then
    show_diff=true
fi

if ! [ -d "$clean_dir" ]; then
    echo "ERROR: Copy of clean source directory not found!"
    echo
    echo "You need to call clean-check-prepare on the clean source directory before using"
    echo "clean-check."
    exit 1
fi

trap 'rm -rf "$diff"' EXIT
diff="$(mktemp)"

if [ "$show_diff" == true ]; then
    diff_opts="-u"
else
    diff_opts="-q"
fi

ok=true
diff "$diff_opts" -x .git -r "$clean_dir" "$top_dir" > "$diff" || ok=false

if [ "$ok" == true ]; then
    echo "Source tree is unchanged. :]"
    exit 0
fi

echo "================================================================================"
echo "                ERROR: Source tree is not unchanged after clean:"
echo "--------------------------------------------------------------------------------"
cat "$diff"
echo "================================================================================"
exit 1
