#!/usr/bin/env bash
set -e

# Determine CMake flags

declare -a CMAKE_FLAGS

echo "Build configuration:"

case "$HARDEN" in
  on)
    echo " * enable hardening"
    CMAKE_FLAGS+=(-DHARDEN=ON);;
  off) ;;
  *)
    echo "Unexpected HARDEN value: $HARDEN" >&2
    exit 1;;
esac

case "$ASAN" in
  on)
    echo " * enable AddressSanitizer"
    CMAKE_FLAGS+=(-DASAN=ON);;
  off) ;;
  *)
    echo "Unexpected ASAN value: $ASAN" >&2
    exit 1;;
esac

case "$MOSTLY_STATIC" in
  on)
    echo " * mostly static build"
    # We will not build OCI because of static linking issues with curl
    CMAKE_FLAGS+=(-DBUILD_MOSTLY_STATIC=ON -DOPENSSL_USE_STATIC_LIBS=TRUE -DZLIB_USE_STATIC_LIBS=TRUE -DOCI=OFF);;
  off) ;;
  *)
    echo "Unexpected MOSTLY_STATIC value: $MOSTLY_STATIC" >&2
    exit 1;;
esac

case "$ONLY_RECC_WITH_CLANG_SCAN_DEPS" in
  on)
    echo " * build only RECC with clang-scan-deps"
    CMAKE_FLAGS+=(-DTOOLS=OFF -DOCI=OFF -DRECC=ON -DCLANG_SCAN_DEPS=ON);;
  off) ;;
  *)
    echo "Unexpected ONLY_RECC_WITH_CLANG_SCAN_DEPS value: $ONLY_RECC_WITH_CLANG_SCAN_DEPS" >&2
    exit 1;;
esac

case "$UNIT_TESTS" in
  on)
    # if INSTALL is set then error
    if [ "$INSTALL" = on ]; then
      echo "UNIT_TESTS is on and INSTALL is on.  This is not supported." >&2
      exit 1
    fi
    echo " * build unit tests";;
  off)
    CMAKE_FLAGS+=(-DBUILD_TESTING=OFF);;
  *)
    echo "Unexpected UNIT_TESTS value: $UNIT_TESTS" >&2
    exit 1;;
esac

case "$COVERAGE" in
  on)
    echo " * enable coverage"
    CMAKE_FLAGS+=(-DCOVERAGE=ON);;
  off) ;;
  *)
    echo "Unexpected COVERAGE value: $COVERAGE" >&2
    exit 1;;
esac

case "$BUILD_TYPE" in
  "")
    echo "Unexpected missing BUILD_TYPE" >&2
    exit 1;;
  *)
    echo " * build type is $BUILD_TYPE"
    CMAKE_FLAGS+=(-DCMAKE_BUILD_TYPE=$BUILD_TYPE);;
esac

# If BUILD_TARGETS is set then echo the value
if [ -n "$BUILD_TARGETS" ]; then
    # if INSTALL is set then error
    if [ "$INSTALL" = on ]; then
      echo "BUILD_TARGETS is set and INSTALL is on.  This is not supported." >&2
      exit 1
    fi
  echo " * building target: $BUILD_TARGETS"
fi

case "$INSTALL" in
  on)
    echo " * installing binaries";;
  off) ;;
  *)
    echo "Unexpected INSTALL value: $INSTALL" >&2
    exit 1;;
esac
CMAKE_FLAGS+=(-DCMAKE_EXPORT_COMPILE_COMMANDS=ON)
CMAKE_FLAGS+=(-DCMAKE_CXX_STANDARD=23)
echo "CMake flags: ${CMAKE_FLAGS}"

# Add non-root user for devcontainer use
groupadd -r builder
useradd --shell /bin/bash -m -r -g builder builder
echo "builder ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers

mkdir -p /buildbox/build
cd /buildbox/build

cmake -G Ninja ${CMAKE_FLAGS[@]} ..
if [ -n "$BUILD_TARGETS" ]; then
  ninja $BUILD_TARGETS
else
  ninja
fi

if [ "$INSTALL" = on ]; then
  ninja install
fi
