#!/bin/bash

# AMOS build script for pymongo

# Copyright 2015-2024  Dimitris Zlatanidis  Orestiada, Greece
# Copyright 2013-2014  Christoph Willing,  Australia
# 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=pymongo
VERSION=${VERSION:-4.18.2}
BUILD=${BUILD:-1}
PKGTYPE=${PKGTYPE:-txz}

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" = "i586" ]; then
  SLKCFLAGS="-O2 -march=i586 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "i686" ]; then
  SLKCFLAGS="-O2 -march=i686 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O2 -fPIC"
  LIBDIRSUFFIX="64"
else
  SLKCFLAGS="-O2"
  LIBDIRSUFFIX=""
fi

# ---------------------------------------------------------------------------
# HARDENING — matches the tree-wide default from make_world
#
# -fhardened is the GCC 14+ umbrella flag and is what every other package
# in the tree receives via the CUSTOM_BUILD_HARDENED patch. On GCC 14 it
# expands to:
#
#   -fstack-protector-strong       (canary)
#   -fstack-clash-protection
#   -D_FORTIFY_SOURCE=3            (FORTIFY level 3)
#   -fPIE                          (PIE codegen)
#   -fcf-protection=full           (CET: endbr64 + IBT note in each object)
#   -ftrivial-auto-var-init=zero
#
# The linker-side CET flags are deliberately separate. -fcf-protection=full
# marks each object file with the IBT property; the linker only propagates
# that property to the final output when told to. Without -Wl,-z,ibt the
# property is dropped and the audit sees T=0.
#
# GNU ld is used here (no -fuse-ld override), which recognizes -z ibt and
# -z shstk. LLD would need -z force-ibt instead; that substitution only
# applies when a SlackBuild explicitly selects lld.
#
# No -pie on the link line: PyMongo builds shared objects (Type: DYN),
# which already satisfy the audit's PIE check. -fhardened does not leak
# -pie onto the link line because it is only set in CFLAGS/CXXFLAGS, not
# in LDFLAGS, and LDFLAGS is what the Python extension build consumes
# for its link step.
# ---------------------------------------------------------------------------
export CC=gcc
export CXX=g++

export CFLAGS="$SLKCFLAGS -fhardened"
export CXXFLAGS="$SLKCFLAGS -fhardened"
export 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 $PRGNAM-$VERSION
tar xvf $CWD/$PRGNAM-$VERSION.tar.gz
cd $PRGNAM-$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 {} \;

# ---------------------------------------------------------------------------
# Remove the hatch metadata hook and re-declare the extras it provided.
#
# pyproject.toml declares two build-system requirements beyond
# hatchling: hatch-requirements-txt>=0.4.1. That plugin is not
# installed on the build host, and installing it would add a pip
# package to the build environment for the sole purpose of reading
# three text files. Instead:
#
#   1. Strip the requirement from [build-system].requires.
#   2. Delete the [tool.hatch.metadata.hooks.requirements_txt] and
#      [tool.hatch.metadata.hooks.requirements_txt.optional-dependencies]
#      sections.
#   3. Append a plain [project.optional-dependencies] table with the
#      same contents, read from requirements/{aws,docs,encryption}.txt
#      in the upstream tarball. Hatchling reads this table natively,
#      no plugin required, and produces the same wheel metadata.
#
# The unrelated [tool.hatch.build.hooks.custom] section at
# pyproject.toml:82 stays. It runs hatch_build.py during the wheel
# build to compile the extension modules and does not use the plugin.
# ---------------------------------------------------------------------------

# 1. Strip the plugin from build-system.requires
sed -i -E 's/,"hatch-requirements-txt[^"]*"//; s/"hatch-requirements-txt[^"]*",//' pyproject.toml

# 2. Delete the metadata hook sections. The pattern matches both
#    the main section and its .optional-dependencies subsection.
awk '
  /^\[tool\.hatch\.metadata\.hooks\.requirements_txt/ { skip=1; next }
  /^\[/ { skip=0 }
  !skip { print }
' pyproject.toml > pyproject.toml.new
mv pyproject.toml.new pyproject.toml

# 2b. Drop 'optional-dependencies' from the dynamic list.
sed -i -E 's/, ?"optional-dependencies"//g; s/"optional-dependencies", ?//g' pyproject.toml

# 3. Re-declare the extras as a standard PEP 621 table. Contents
#    mirror requirements/aws.txt, requirements/docs.txt, and
#    requirements/encryption.txt from the tarball.
cat >> pyproject.toml <<'PYPROJECT_EOF'

[project.optional-dependencies]
aws = [
    "pymongo-auth-aws>=1.3.0,<2.0.0",
]
docs = [
    "sphinx>=5.3,<9",
    "sphinx_rtd_theme>=3.1.0,<4",
    "readthedocs-sphinx-search~=0.3",
    "sphinxcontrib-shellcheck>=1.1.2,<2",
    "sphinx-autobuild>=2024.10.3",
    "furo==2025.12.19",
]
encryption = [
    "pymongo-auth-aws>=1.3.0,<2.0.0",
    "pymongocrypt>=1.18.1,<2.0.0",
    "certifi>=2023.7.22;os.name=='nt' or sys_platform=='darwin'",
]
PYPROJECT_EOF

# Sanity: fail if the edit did not take. Without this, a future
# upstream change to the hook section name would silently produce
# a wheel with no extras metadata.
if grep -q 'requirements_txt' pyproject.toml; then
  echo "FAIL: requirements_txt hook still present after edit" >&2
  exit 1
fi
if ! grep -q '^\[project\.optional-dependencies\]' pyproject.toml; then
  echo "FAIL: [project.optional-dependencies] was not appended" >&2
  exit 1
fi

PYVER=$(python3 -c 'import sys; print("%d.%d" % sys.version_info[:2])')

# python3-setuptools-opt is NOT required for pymongo 4.18.x. The package
# uses hatchling as its PEP 517 backend and does not import pkg_resources
# at build time. Prefer it only if it happens to be installed.
if [ -d "/opt/python${PYVER}/site-packages" ]; then
  export PYTHONPATH="/opt/python${PYVER}/site-packages${PYTHONPATH:+:$PYTHONPATH}"
fi

python3 -m build --no-isolation
python3 -m installer -d "$PKG" dist/*.whl

# Verify the wheel carries the extras metadata.
echo "--- extras metadata check ---"
METADATA=$(unzip -p dist/*.whl '*/METADATA' 2>/dev/null || true)
for extra in aws docs encryption; do
  grep -q "^Provides-Extra: $extra$" <<< "$METADATA" \
    || { echo "FAIL: wheel has no Provides-Extra: $extra"; exit 1; }
done
echo "--- extras metadata check passed ---"

# Verify the compiled extensions picked up the hardening flags. If any
# of these greps fail, the extension was built without hardening and
# the build should fail rather than ship a package that will flunk the
# audit.
echo "--- hardening check on compiled extensions ---"
for so in $(find "$PKG" -name '*.so' -type f); do
  echo "checking: $so"
  readelf -d "$so" | grep -q BIND_NOW \
    || { echo "FAIL: $so has no BIND_NOW (no full RELRO)"; exit 1; }
  readelf -lW "$so" | grep -q GNU_RELRO \
    || { echo "FAIL: $so has no GNU_RELRO"; exit 1; }
  readelf -lW "$so" | grep GNU_STACK | grep -q ' RWE ' \
    && { echo "FAIL: $so has an executable stack"; exit 1; } || true
  readelf -nW "$so" | grep -q IBT \
    || { echo "FAIL: $so has no IBT property"; exit 1; }
  readelf -nW "$so" | grep -q SHSTK \
    || { echo "FAIL: $so has no SHSTK property"; exit 1; }
done
echo "--- hardening check passed ---"

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
for f in LICENSE README.md THIRD-PARTY-NOTICES CONTRIBUTING.md; do
    [ -e "$f" ] && cp -a "$f" $PKG/usr/doc/$PRGNAM-$VERSION/
done
[ -f doc/changelog.rst ] && cp -a doc/changelog.rst $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.txz
