#!/bin/bash
# CUSTOM_BUILD_HARDENED
# AM·OS build script for mongodb
# Copyright 2026 ANNE Media
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

cd $(dirname $0) ; CWD=$(pwd)

PRGNAM=mongodb
SRCNAM=mongo
VERSION=${VERSION:-8.3.11}
BUILD=${BUILD:-1}
PKGTYPE=${PKGTYPE:-txz}
JOBS=${JOBS:-6}

if [ -z "$ARCH" ]; then
  case "$( uname -m )" in
    i?86) ARCH=i586 ;;
    arm*) ARCH=arm ;;
       *) ARCH=$( uname -m ) ;;
  esac
fi

if [ ! -z "${PRINT_PACKAGE_NAME}" ]; then
  echo "$PRGNAM-$VERSION-$ARCH-$BUILD.$PKGTYPE"
  exit 0
fi

TMP=${TMP:-/tmp/SBo}
PKG=$TMP/package-$PRGNAM
OUTPUT=${OUTPUT:-/tmp}

if [ "$ARCH" = "x86_64" ]; then
  LIBDIRSUFFIX="64"
else
  LIBDIRSUFFIX=""
fi

set -e

# If RESUME=1, skip the extraction, patches, toolchain install, and the
# bazel build; assume the tree at $TMP/$SRCNAM-r$VERSION already contains
# a completed build under bazel-bin/. Re-run only the hardening check and
# packaging steps. Use this after a successful build to repack without
# paying for 14,000 compile actions again.
RESUME=${RESUME:-0}

rm -rf $PKG
mkdir -p $TMP $PKG $OUTPUT

if [ "$RESUME" = "1" ]; then
    echo ">>> RESUME=1: skipping extraction, patches, toolchain, and bazel build"
    if [ ! -d "$TMP/$SRCNAM-r$VERSION" ]; then
        echo "FAIL: $TMP/$SRCNAM-r$VERSION does not exist; cannot resume" >&2
        exit 1
    fi
    if [ ! -f "$TMP/$SRCNAM-r$VERSION/bazel-bin/install/bin/mongod" ]; then
        echo "FAIL: $TMP/$SRCNAM-r$VERSION/bazel-bin/install/bin/mongod missing" >&2
        exit 1
    fi
    cd "$TMP/$SRCNAM-r$VERSION"
else

cd $TMP
rm -rf $SRCNAM-r$VERSION
tar xvf $CWD/$SRCNAM-r$VERSION.tar.gz
cd $SRCNAM-r$VERSION
chown -R root:root .
find -L . \
 \( -perm 777 -o -perm 775 -o -perm 750 -o -perm 711 -o -perm 555 \
  -o -perm 511 \) -exec chmod 755 {} \; -o \
 \( -perm 666 -o -perm 664 -o -perm 640 -o -perm 600 -o -perm 444 \
  -o -perm 440 -o -perm 400 \) -exec chmod 644 {} \;

# ---------------------------------------------------------------------------
# MONGOS LINK DEPENDENCY PATCH
#
# mongos fails to link because router_exec_stage and sharding_router_api
# reference TransactionParticipantResourceYielder::make, which lives in
# //src/mongo/db/transaction:transaction. That library transitively depends
# on the referencing libraries, so it cannot be added to them without a
# cycle. The dep belongs on the leaf binary target instead.
# ---------------------------------------------------------------------------
# valid patch, but we won't ship mongos target anyway, so...
# python3 - <<'PYEOF'
# p = "src/mongo/s/BUILD.bazel"
# s = open(p).read()
# needle = '        "//src/mongo/db/transaction:transaction",\n'
# if needle in s:
#     print("already patched"); raise SystemExit
# old = ('        "mongos_main",\n'
#        '        "//src/mongo/db:server_base",\n'
#        '        "mongos_res",\n')
# new = ('        "mongos_main",\n'
#        '        "//src/mongo/db:server_base",\n'
#        '        "//src/mongo/db/transaction:transaction",\n'
#        '        "mongos_res",\n')
# assert old in s, "mongos binary deps anchor not found"
# s = s.replace(old, new, 1)
# open(p, "w").write(s)
# print("patched")
# PYEOF
#
# if ! grep -q '"//src/mongo/db/transaction:transaction"' src/mongo/s/BUILD.bazel; then
#     echo "FAIL: mongos transaction dep patch did not apply" >&2
#     exit 1
# fi

# ---------------------------------------------------------------------------
# INSTALL CUSTOM SYSTEM-GCC TOOLCHAIN
#
# Register a cc_toolchain that points at /usr/bin/gcc instead of the
# hermetic mongo_toolchain_v5. --extra_toolchains takes priority over
# register_toolchains, so this toolchain is selected for every C/C++
# action.
#
# The hardening flags (-fstack-protector-strong, -D_FORTIFY_SOURCE=3,
# -fcf-protection=full, -Wl,-z,relro,-z,now,-z,force-ibt,-z,shstk, and so
# on) are declared inside the toolchain config file, not on the command
# line. They apply to every compile and link action the build performs.
# ---------------------------------------------------------------------------
TOOLCHAIN_DIR="bazel/toolchains/cc/system_gcc"
mkdir -p "$TOOLCHAIN_DIR"

GCC_INC=$(gcc -print-file-name=include)
if [ -z "$GCC_INC" ] || [ "$GCC_INC" = "include" ]; then
    echo "FAIL: gcc -print-file-name=include returned nothing useful" >&2
    exit 1
fi

GCC_CXX_VER=$(ls -d /usr/include/c++/[0-9]*/ 2>/dev/null \
    | sed 's,/*$,,; s,.*/,, ' \
    | sort -V \
    | tail -1)
if [ -z "$GCC_CXX_VER" ]; then
    echo "FAIL: no /usr/include/c++/<version>/ directory found" >&2
    exit 1
fi

if [ ! -d "/usr/include/c++/$GCC_CXX_VER/x86_64-slackware-linux" ]; then
    echo "FAIL: /usr/include/c++/$GCC_CXX_VER/x86_64-slackware-linux not found" >&2
    exit 1
fi

GCC_VERSION_DIR=$(dirname "$GCC_INC")
echo ">>> System GCC version directory:  $GCC_VERSION_DIR"
echo ">>> System C++ headers version:   $GCC_CXX_VER"

cp "$CWD/system_gcc_cc_toolchain_config.bzl" "$TOOLCHAIN_DIR/cc_toolchain_config.bzl"
cp "$CWD/system_gcc_BUILD.bazel"             "$TOOLCHAIN_DIR/BUILD.bazel"
cp "$CWD/system_gcc_preinclude.h"            "$TOOLCHAIN_DIR/preinclude.h"

sed -i "s|/usr/include/c++/16\.2\.0|/usr/include/c++/$GCC_CXX_VER|g" \
    "$TOOLCHAIN_DIR/cc_toolchain_config.bzl"
sed -i "s|/usr/lib64/gcc/x86_64-slackware-linux/16\.2\.0|$GCC_VERSION_DIR|g" \
    "$TOOLCHAIN_DIR/cc_toolchain_config.bzl"

if ! grep -q "/usr/include/c++/$GCC_CXX_VER" "$TOOLCHAIN_DIR/cc_toolchain_config.bzl"; then
    echo "FAIL: toolchain config does not reference /usr/include/c++/$GCC_CXX_VER" >&2
    exit 1
fi
if ! grep -q "$GCC_VERSION_DIR" "$TOOLCHAIN_DIR/cc_toolchain_config.bzl"; then
    echo "FAIL: toolchain config does not reference $GCC_VERSION_DIR" >&2
    exit 1
fi

if [ ! -f "$TOOLCHAIN_DIR/BUILD.bazel" ] || [ ! -f "$TOOLCHAIN_DIR/cc_toolchain_config.bzl" ] || [ ! -f "$TOOLCHAIN_DIR/preinclude.h" ]; then
    echo "FAIL: toolchain files not copied to $TOOLCHAIN_DIR" >&2
    exit 1
fi

# ---------------------------------------------------------------------------
# .bazelrc PATCHING
#
#   1. Disable the Atlas module. It is MongoDB's managed-cloud feature
#      set, not needed for the community server.
#
#   2. Cap parallel jobs at 8. MongoDB's .bazelrc sets --jobs=300 for
#      their 96-core CI machines and --jobs=auto inside the [local]
#      config. Both would launch more parallel compiles than a
#      workstation can hold in memory. Substituting 8 keeps every
#      invocation of bazel within the machine's budget.
# ---------------------------------------------------------------------------
echo ">>> Patching .bazelrc..."

sed -i '/build_atlas=True/d' .bazelrc
echo 'common --//bazel/config:build_atlas=False' >> .bazelrc

sed -i -E "s/^common --jobs=[0-9]+\$/common --jobs=$JOBS/" .bazelrc
sed -i -E "s/^common:clang-tidy --jobs=[0-9]+\$/common:clang-tidy --jobs=$JOBS/" .bazelrc
sed -i -E "s/--jobs=auto\$/--jobs=$JOBS/" .bazelrc

if ! grep -q 'build_atlas=False' .bazelrc; then
    echo "FAIL: .bazelrc has no build_atlas=False" >&2
    exit 1
fi
if grep -q 'jobs=300' .bazelrc; then
    echo "FAIL: --jobs=300 still present in .bazelrc" >&2
    exit 1
fi
if grep -q 'jobs=auto' .bazelrc; then
    echo "FAIL: --jobs=auto still present in .bazelrc" >&2
    exit 1
fi

# ---------------------------------------------------------------------------
# BAZELISK SETUP
#
# MongoDB pins a custom Bazel fork: 7.5.0-mongo_06d753863d. It is hosted
# on MongoDB's public S3 bucket and referenced by .bazeliskrc. A system
# Bazel 9.x is the wrong version.
# ---------------------------------------------------------------------------
echo ">>> Installing MongoDB's Bazelisk (via install_bazel.py)..."
python3 buildscripts/install_bazel.py

BAZELISK="$HOME/.local/bin/bazelisk"
if [ ! -x "$BAZELISK" ]; then
    echo "FAIL: bazelisk not installed at $BAZELISK" >&2
    exit 1
fi

echo ">>> Bazel version (via Bazelisk):"
"$BAZELISK" --version

# ---------------------------------------------------------------------------
# ENVIRONMENT SANITIZATION
# ---------------------------------------------------------------------------
unset USE_NATIVE_TOOLCHAIN
unset BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN
unset CC CXX AR LD RANLIB

# ---------------------------------------------------------------------------
# BUILD
#
# --host_jvm_args is a startup flag; it must come before 'build'.
#
# --check_direct_dependencies=off silences the MODULE.bazel version
# mismatch warnings (apple_support, bazel_features, rules_cc).
#
# --define=MONGO_DISTMOD selects the platform constraint.
#
# --extra_toolchains selects the custom system-gcc toolchain.
#
# --local_resources=memory=16000 and the cache flags keep the build
# within the machine's memory budget. The jobs count is supplied by
# .bazelrc (patched above to $JOBS).
#
# --disable_warnings_as_errors is a MongoDB flag alias. GCC 16.2.0
# produces warnings that MongoDB's hermetic GCC 14.2.0 does not, and
# without this flag those warnings would abort the build.
#
# Feature disables:
#   --build_enterprise=False   drop the enterprise source tree
#   --disable_streams=True     drop the enterprise streams module
#   --build_otel=False         drop OpenTelemetry and protoc
#   --js_engine=none           drop SpiderMonkey (mozjs) entirely; also
#                              makes $where, $function, $accumulator, and
#                              mapReduce unavailable at runtime. Pair with
#                              security.javascriptEnabled=false in mongod.conf.
#   --server_js=False          belt-and-braces; js_engine=none is the
#                              flag that removes mozjs from the graph.
#   --linkopt="-s"             strip debug symbols during the link instead
#                              of post-hoc. Matches what the SlackBuild's
#                              strip pass would do anyway.
#
# The four empty-endpoint flags blank the EngFlow remote execution
# endpoints. External builders cannot authenticate there.
# ---------------------------------------------------------------------------
echo ">>> Shutting down any previous Bazel server..."
"$BAZELISK" shutdown
# "$BAZELISK" clean --expunge
# rm -rf /root/.cache/bazel/_bazel_root

echo ">>> Building MongoDB (this will take a while)..."
"$BAZELISK" --host_jvm_args=-Xmx4g build \
    --check_direct_dependencies=off \
    --define=MONGO_DISTMOD=amos64 \
    --define=MONGO_DISTARCH=x86_64 \
    --define=MONGO_VERSION=${VERSION} \
    --extra_toolchains=//bazel/toolchains/cc/system_gcc:system_gcc_toolchain_def \
    --local_resources=memory=16000 \
    --discard_analysis_cache \
    --build_enterprise=False \
    --disable_streams=True \
    --build_otel=False \
    --js_engine=none \
    --server_js=False \
    --linkopt="-s" \
    --keep_going \
    --nokeep_state_after_build \
    --notrack_incremental_state \
    --disable_warnings_as_errors=True \
    --per_file_copt=.*@-Wno-error=unused-result,-Wno-error=attribute-alias,-Wno-error=deprecated-declarations,-Wno-error=stringop-overflow,-Wno-error=array-bounds \
    --bes_backend= \
    --remote_cache= \
    --remote_executor= \
    --experimental_remote_downloader= \
    install-mongod

fi   # end of RESUME=0 branch
    # install-mongod install-mongos
# ---------------------------------------------------------------------------
# HARDENING VERIFICATION
# ---------------------------------------------------------------------------
echo "--- hardening check on built binaries ---"
#for BIN in bazel-bin/install/bin/mongod bazel-bin/install/bin/mongos; do
for BIN in bazel-bin/install/bin/mongod; do
    if [ ! -f "$BIN" ]; then
        echo "FAIL: $BIN not found"
        exit 1
    fi
    echo "checking: $BIN"
    readelf -d "$BIN" | grep -q BIND_NOW \
        || { echo "FAIL: $BIN has no BIND_NOW (no full RELRO)"; exit 1; }
    readelf -lW "$BIN" | grep -q GNU_RELRO \
        || { echo "FAIL: $BIN has no GNU_RELRO"; exit 1; }
    readelf -lW "$BIN" | grep GNU_STACK | grep -q ' RWE ' \
        && { echo "FAIL: $BIN has an executable stack"; exit 1; } || true
    readelf -nW "$BIN" | grep -q IBT \
        || { echo "FAIL: $BIN has no IBT property"; exit 1; }
    readelf -nW "$BIN" | grep -q SHSTK \
        || { echo "FAIL: $BIN has no SHSTK property"; exit 1; }
done
echo "--- hardening check passed ---"

# ---------------------------------------------------------------------------
# INSTALL
# ---------------------------------------------------------------------------
mkdir -p $PKG/usr/bin
cp bazel-bin/install/bin/mongod $PKG/usr/bin/
# cp bazel-bin/install/bin/mongos $PKG/usr/bin/




find $PKG -print0 | xargs -0 file | grep -e "executable" -e "shared object" | grep ELF \
  | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null || true

mkdir -p $PKG/usr/doc/$PRGNAM-$VERSION
cp -a LICENSE-Community.txt README.md $PKG/usr/doc/$PRGNAM-$VERSION 2>/dev/null || true
cat "$CWD/$(basename "$0")" > $PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM.SlackBuild

mkdir -p $PKG/etc/{logrotate,rc}.d
cat $CWD/files/mongod.conf > $PKG/etc/mongod.conf.new
# cat $CWD/files/mongos.conf > $PKG/etc/mongos.conf.new
cat $CWD/files/mongo.logrotate > $PKG/etc/logrotate.d/mongo.new
cat $CWD/files/rc.mongodb > $PKG/etc/rc.d/rc.mongodb.new
chmod 755 $PKG/etc/rc.d/rc.mongodb.new

mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc
cat $CWD/doinst.sh > $PKG/install/doinst.sh

cd $PKG
/sbin/makepkg -l y -c n $OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.txz
