#! /bin/sh

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

# Find the top-level WiredTiger directory and move to there.
top=`git rev-parse --show-toplevel` && cd $top || exit 1
echo "$0: running clang-tidy in $PWD"

# Clang isn't installed in any standard place, find a binary we can use.
# If the caller gives us $CLANGTIDY, use it.
tidy="$CLANGTIDY"

if test -z "$tidy" &&
    test -x /usr/lib/llvm-3.9/bin/clang-tidy; then
	tidy="/usr/lib/llvm-3.9/bin/clang-tidy"
fi

if test -z "$tidy"; then
	echo "$0: no clang-tidy programs found"
	echo "$0: set \$CLANGTIDY=/path/clang-tidy to continue"
	exit 1
fi
echo "$0: clang-tidy: $tidy"

rm -rf ${t_pfx}build && mkdir ${t_pfx}build
(cd ${t_pfx}build &&
    cmake -DHAVE_DIAGNOSTIC=1 -DENABLE_STRICT=1 ../.) > /dev/null || exit 1

# We need a custom wiredtiger_config.h, clang-tidy doesn't know where to
# find the x86intrin.h include file.
cp ${t_pfx}build/config/wiredtiger_config.h $t
sed '/HAVE_X86INTRIN_H/d' < $t > ${t_pfx}build/config/wiredtiger_config.h

# We need a custom verify_build.h, clang-tidy doesn't like the magic.
f=src/include/verify_build.h
cat $f > $f.save
echo '#define WT_STATIC_ASSERT(a)' > $f

def="-D_GNU_SOURCE"
inc="-I${t_pfx}build/config -I${t_pfx}build/include -Isrc/include"

args="-checks=*"
args="$args,-android-cloexec-fopen"
args="$args,-clang-analyzer-core.NullDereference"
args="$args,-clang-analyzer-optin.performance.Padding"
args="$args,-clang-analyzer-valist.Uninitialized"
args="$args,-cppcoreguidelines-avoid-magic-numbers"
args="$args,-google-readability-braces-around-statements"
args="$args,-hicpp-braces-around-statements"
args="$args,-hicpp-multiway-paths-covered"
args="$args,-hicpp-no-assembler"
args="$args,-hicpp-signed-bitwise"
args="$args,-hicpp-uppercase-literal-suffix"
args="$args,-hicpp-uppercase-literal-suffix-header-guard"
args="$args,-llvm-header-guard"
args="$args,-llvm-include-order"
args="$args,-readability-braces-around-statements"
args="$args,-readability-inconsistent-declaration-parameter-name"
args="$args,-readability-magic-numbers"
args="$args,-readability-named-parameter"
args="$args,-readability-non-const-parameter"
args="$args,-readability-uppercase-literal-suffix"

# Only specify -header once.
f=src/btree/bt_compact.c
$tidy --quiet $f "-header-filter=.*,$args" -- $def $inc > $t

f=`echo src/[a-np-z]*/*.c src/os_posix/*.c`
$tidy --quiet $f "$args" -- $def $inc >> $t

# Restore verify_build.h.
f=src/include/verify_build.h
cat $f.save > $f
rm -f $f.save

echo "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="
echo 'clang-tidy output'
echo "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="
cat $t

exit 0
