#!/bin/bash
# CUSTOM_BUILD_HARDENED
# AMOS build script for mongodb-shell
# 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-shell
SRCNAM=mongosh
VERSION=${VERSION:-2.13.0}
BUILD=${BUILD:-1}
PKGTYPE=${PKGTYPE:-txz}

ARCH=x86_64

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}

# ---- hardening flags (applied to native modules compiled via node-gyp) ----
export CFLAGS="${CFLAGS:-} -O2 -fPIC -fstack-protector-strong -D_FORTIFY_SOURCE=3"
export CXXFLAGS="${CXXFLAGS:-} -O2 -fPIC -fstack-protector-strong -D_FORTIFY_SOURCE=3"
export LDFLAGS="${LDFLAGS:-} -Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack -Wl,-z,ibt -Wl,-z,shstk"

set -e

rm -rf $PKG
mkdir -p $TMP $PKG $OUTPUT
cd $TMP
rm -rf $SRCNAM-$VERSION
tar xvf $CWD/$SRCNAM-$VERSION.tar.gz
cd $SRCNAM-$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 {} \;

# ---------------------------------------------------------------------------
# Security overrides. Anything listed here is a deliberate, pinned deviation
# from upstream's lockfile. Filling this in requires running
#   npm audit --omit=dev --json
# and picking advisories that (a) affect the runtime tree and (b) have a
# patched version inside the current semver range.
#
# Example (replace with real entries from your audit output):
#
#   node -e '
#     const fs=require("fs");
#     const pkg=JSON.parse(fs.readFileSync("packages/cli-repl/package.json"));
#     pkg.overrides = {
#       "tar": "^6.2.1",
#       "minimatch": "^9.0.5"
#     };
#     fs.writeFileSync("packages/cli-repl/package.json",
#                      JSON.stringify(pkg, null, 2));
#   '
#
# If you add entries, bump BUILD in this script and document them in
# README.slackware (see below).
# ---------------------------------------------------------------------------
# <-- overrides go here, before "npm ci" runs.

# ---------------------------------------------------------------------------
# npm 12 blocks install scripts by default. We need them to run because
# node-gyp rebuilds are how our hardening flags reach the native modules.
# ---------------------------------------------------------------------------
export npm_config_build_from_source=true
export SEGMENT_API_KEY=dummy

# Approve the specific packages that ship native code we want rebuilt.
# (Run "npm install-scripts ls" after the first install to review the full
# list if this one changes between releases.)
for pkg in \
    @mongodb-js/native-machine-id \
    cpu-features \
    glibc-version \
    interruptor \
    kerberos \
    mongodb-client-encryption \
    mongodb-crypt-library-version \
    os-dns-native \
    ssh2 ; do
  npm install-scripts approve "$pkg" 2>/dev/null || true
done

# Install dependencies. Do NOT pass --ignore-scripts: we want node-gyp to
# rebuild the native modules so CFLAGS/CXXFLAGS/LDFLAGS apply.
npm ci

# Bootstrap the monorepo and compile the CLI.
npm run bootstrap
npm run compile-cli

# ---------------------------------------------------------------------------
# Informational audit — recorded in the build log so deviations are visible.
# This does NOT modify anything.
# ---------------------------------------------------------------------------
echo "--- runtime advisories (informational) ---"
npm audit --omit=dev --production || true
echo "-------------------------------------------"

# ---------------------------------------------------------------------------
# Prune build-only dependencies. Lerna, Nx, and TypeScript ship prebuilt
# Rust binaries that never see our hardening flags and have no business in
# the shipped tree.
# ---------------------------------------------------------------------------
npm prune --omit=dev || true
rm -rf node_modules/lerna node_modules/nx node_modules/@nx \
       node_modules/typescript node_modules/@types 2>/dev/null || true
rm -rf node_modules/.bin 2>/dev/null || true

# Slackware is glibc-only; scrub any musl native binaries that survived.
find node_modules -type d -name '*-musl' -exec rm -rf {} + 2>/dev/null || true
find node_modules -name '*musl*.node' -delete 2>/dev/null || true

# Strip node-gyp build intermediates; only build/Release/*.node
# belongs in a package. Removes the duplicate cpufeatures.node.
find node_modules -type d \( -name 'obj.target' -o -name '.deps' \) \
    -prune -exec rm -rf {} + 2>/dev/null || true
# ---------------------------------------------------------------------------
# Locate the CLI entry point.
# ---------------------------------------------------------------------------
MONGOSH_JS=$(find packages/cli-repl -type f -name 'mongosh.js' \
  -not -path '*/node_modules/*' -not -path '*/src/*' | head -n1)

if [ -z "$MONGOSH_JS" ]; then
  echo "ERROR: mongosh.js not found. Diagnostic dump below."
  ls -la packages/cli-repl
  find packages/cli-repl -type f -name '*.js' \
    -not -path '*/node_modules/*' -not -path '*/src/*' | head -60
  grep -R '"outDir"' packages/cli-repl/tsconfig*.json 2>/dev/null || true
  exit 1
fi
echo "Using CLI entry point: $MONGOSH_JS"

# ---------------------------------------------------------------------------
# Install the compiled CLI tree + runtime dependencies.
# bin/mongosh.js requires ../package.json, and node_modules must be a real
# directory tree (not symlinks) so it works outside the build chroot.
# ---------------------------------------------------------------------------
mkdir -p $PKG/usr/lib64/$PRGNAM $PKG/usr/bin $PKG/usr/man/man1

cp -a packages/cli-repl/bin $PKG/usr/lib64/$PRGNAM/
cp -a packages/cli-repl/lib $PKG/usr/lib64/$PRGNAM/
cp -a packages/cli-repl/package.json $PKG/usr/lib64/$PRGNAM/
cp -aL node_modules $PKG/usr/lib64/$PRGNAM/
find $PKG -name 'cpufeatures.node' -print

cat > $PKG/usr/bin/mongosh <<'EOF'
#!/bin/sh
exec node /usr/lib64/mongodb-shell/bin/mongosh.js "$@"
EOF
chmod 0755 $PKG/usr/bin/mongosh

# Native crypt library, if built.
CRYPT_LIB=$(find packages -name 'mongosh_crypt_v1.so' | head -n1)
if [ -n "$CRYPT_LIB" ]; then
  install -m 0755 "$CRYPT_LIB" $PKG/usr/lib64/
fi

if [ -f mongosh.1.gz ]; then
  cp mongosh.1.gz $PKG/usr/man/man1/
fi

[ -f $PKG/usr/lib64/mongosh_crypt_v1.so ] && \
  strip --strip-unneeded $PKG/usr/lib64/mongosh_crypt_v1.so

# ---------------------------------------------------------------------------
# Smoke test.
# ---------------------------------------------------------------------------
echo "--- smoke test ---"
node $PKG/usr/lib64/$PRGNAM/bin/mongosh.js --version || true

# ---------------------------------------------------------------------------
# Documentation.
# ---------------------------------------------------------------------------
mkdir -p $PKG/usr/doc/$PRGNAM-$VERSION
for f in LICENSE LICENSE.md LICENSE.txt README README.md README.txt \
         THIRD_PARTY_NOTICES THIRD-PARTY-NOTICES THIRD_PARTY_NOTICES.md; do
  [ -f "$f" ] && cp -a "$f" $PKG/usr/doc/$PRGNAM-$VERSION/
done
[ -f packages/cli-repl/README.md ] && \
  cp -a packages/cli-repl/README.md $PKG/usr/doc/$PRGNAM-$VERSION/
cat $CWD/$PRGNAM.SlackBuild > $PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM.SlackBuild

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

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