#! /bin/bash

set -o pipefail

t=__wt.$$
trap 'rm -rf $t' 0 1 2 3 13 15

download_clang_format() {
	if [ `uname` = "Linux" ]; then
		curl https://s3.amazonaws.com/boxes.10gen.com/build/clang-format-llvm-10.0.0-x86_64-linux-gnu-ubuntu-20.04.tar-1.gz -o dist/clang-format.tar.gz
		tar --strip=1 -C dist/ -xf dist/clang-format.tar.gz clang-format-llvm-10.0.0-x86_64-linux-gnu-ubuntu-20.04/clang-format && rm dist/clang-format.tar.gz
	elif [ `uname` = "Darwin" ]; then
		curl https://s3.amazonaws.com/boxes.10gen.com/build/build/clang-format-llvm-10.0.0-x86_64-apple-darwin.tar.gz -o dist/clang-format.tar.gz
		tar --strip=1 -C dist/ -xf dist/clang-format.tar.gz clang-format-llvm-10.0.0-x86_64-apple-darwin/clang-format && rm dist/clang-format.tar.gz
	else
		echo "$0: unsupported environment $(uname)"
		exit 1
	fi
}

# Find the top-level WiredTiger directory and move to there.
cd `git rev-parse --show-toplevel` || exit 1

# Override existing Clang Format versions in the PATH.
export PATH="${PWD}/dist":$PATH

# Download the clang-format binary if it's not in place.
[ ! -x "$(command -v clang-format)" ] && download_clang_format

# Ensure that we have the correct version of clang-format.
desired_version="10.0.0"

# On macOS Catalina, users need to manually approve binaries.
# If we're not allowed to run clang-format, let's exit (should be obvious from the dialog).
current_version=`clang-format --version` || exit 1

echo $current_version | grep "version $desired_version" >/dev/null 2>&1
if test $? -ne 0; then
	download_clang_format
fi

case $# in
0)
	# Get all source files that aren't in s_clang-format.list.
	search=`find bench examples ext src test -name '*.[ch]' -o -name '*.cxx' -o -name '*.cpp'`
	for f in `cat dist/s_clang-format.list`; do
		search=`echo "$search" | sed "\#$f#d"`
	done;;
1)
	search="$1";;
*)
	echo "usage: $0 [file]"
	exit 1;;
esac

# Don't format inplace with -i flag.
# We want to be able to detect modifications.
for f in $search; do
	cat "$f" | \
            clang-format --fallback-style=none | \
            python dist/s_comment.py > "$t" || exit 1
	cmp -s "$f" "$t"
	if test $? -ne 0; then
		if test $# -eq 0 ; then
			echo "Modifying $f"
		fi
		cp "$t" "$f"
	fi
done
