#!/usr/bin/env bash

set -e -o pipefail
set -x

BUILD_DIR="${PWD}"

# compilation minimum if nothing got from package builder
export CXXFLAGS=${CXXFLAGS:--fPIC}
export CFLAGS=${CFLAGS:-Wno-error=format-security}

# ensure hardening linker flags (full RELRO + immediate binding)
case "${LDFLAGS}" in
    *-z,relro*) ;;
    *) export LDFLAGS="${LDFLAGS} -Wl,-z,relro" ;;
esac
case "${LDFLAGS}" in
    *-z,now*) ;;
    *) export LDFLAGS="${LDFLAGS} -Wl,-z,now" ;;
esac

if [ -r /etc/os-release ]; then
    . /etc/os-release
    case "$ID" in
        rhel|almalinux)
            export CXXFLAGS="${CXXFLAGS} -DRHEL_FAMILY"
            ;;
    esac
fi

# dump compiler flag
echo '***** Compilation Flags' >&2
echo "- CFLAGS='${CFLAGS}'" >&2
echo "- CXXFLAGS='${CXXFLAGS}'" >&2
echo "- CPPFLAGS='${CPPFLAGS}'" >&2
echo "- LDFLAGS='${LDFLAGS}'" >&2


################################################################################

# Compile OpenNebula
echo '***** Build OpenNebula' >&2

# detects number of CPUs to parallelize build as much as possible
CORES=$(nproc 2>/dev/null)
if [ -z "${CORES}" ] || [ "${CORES}" = '0' ]; then
    CORES=2
fi

cd "${BUILD_DIR}"
"${SCONS:-scons}" -j "${CORES}" \
    mysql=yes grpc=${grpc:-yes} grpcproto=${grpcproto:-yes} \
    "$@"
