#!/usr/bin/env bash

#    Copyright 2020 Couchbase, Inc.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

PROJECT_ROOT="$( cd "$(dirname "$0"/..)" >/dev/null 2>&1 ; pwd -P )"

CB_CMAKE=${CB_CMAKE:-$(which cmake)}
CB_CC=${CB_CC:-$(which clang)}
CB_CXX=${CB_CC:-$(which clang++)}
CB_SCAN_BUILD=${CB_SCAN_BUILD:-$(which scan-build)}

echo "CB_CC=${CB_CC}"
echo "CB_CXX=${CB_CXX}"
echo "CB_SCAN_BUILD=${CB_SCAN_BUILD}"
echo "CB_CMAKE=${CB_CMAKE}"

set -exuo pipefail

BUILD_DIR="${PROJECT_ROOT}/cmake-build-clang-analyzer"
REPORT_DIR="${PROJECT_ROOT}/cmake-build-report"

rm -rf "${BUILD_DIR}" "${REPORT_DIR}"
mkdir -p "${BUILD_DIR}"
cd "${BUILD_DIR}"

SCAN_BUILD_ARGS="--exclude contrib -o ${REPORT_DIR} --use-analyzer=${CB_CC} --use-c++=${CB_CXX} --use-cc=${CB_CC} --status-bugs"

${CB_SCAN_BUILD} ${SCAN_BUILD_ARGS} ${CB_CMAKE} -DLCB_NO_TOOLS=ON ${PROJECT_ROOT}
set +e
${CB_SCAN_BUILD} ${SCAN_BUILD_ARGS} make -j8
STATUS=$?
set -e

tar zcvf ${REPORT_DIR}.tar.gz -C ${REPORT_DIR} .
exit ${STATUS}
