#!/bin/bash

set -eu

CACHEDIR="$HOME/cache"

. ".github/scripts/flags-$CC.sh"
add_flag -Werror
add_flag -D_DEBUG
add_flag -fdiagnostics-color=always
add_flag -fno-omit-frame-pointer
add_flag -fno-sanitize-recover=all
add_flag -fsanitize=undefined,nullability,local-bounds,float-divide-by-zero,integer
add_flag -fno-sanitize=implicit-conversion,unsigned-integer-overflow
# Enable extra checks. We only do this on ubsan because it shows useful error
# messages for the kind of bugs this catches (mostly incorrect nullability
# annotations). Other builds will segfault, ubsan will show a stack trace.
add_flag -D_DEBUG
cmake -B_build -H. -GNinja \
  -DCMAKE_C_FLAGS="$C_FLAGS" \
  -DCMAKE_CXX_FLAGS="$CXX_FLAGS" \
  -DCMAKE_EXE_LINKER_FLAGS="$LD_FLAGS" \
  -DCMAKE_SHARED_LINKER_FLAGS="$LD_FLAGS" \
  -DCMAKE_INSTALL_PREFIX:PATH="$PWD/_install" \
  -DCMAKE_UNITY_BUILD=ON \
  -DMIN_LOGGER_LEVEL=TRACE \
  -DMUST_BUILD_TOXAV=ON \
  -DNON_HERMETIC_TESTS=ON \
  -DSTRICT_ABI=ON \
  -DTEST_TIMEOUT_SECONDS=120 \
  -DUSE_IPV6=OFF \
  -DAUTOTEST=ON

cd _build

ninja install -j"$(nproc)"

export UBSAN_OPTIONS="color=always"
export UBSAN_OPTIONS="$UBSAN_OPTIONS,print_stacktrace=1"
export UBSAN_OPTIONS="$UBSAN_OPTIONS,symbolize=1"
ctest -j50 --output-on-failure --rerun-failed --repeat until-pass:6
