#!/bin/bash
#
# SlackBuild script for libShabal
#
# libShabal is a Rust cdylib. The Rust side is built by cargo; the C
# source files are compiled by build.rs via the cc crate. The Java side
# binds to the resulting .so via JNA from annej.util.LibShabal; the same
# .so is also dropped into the anne-node jar as libshabal.so.
#

cd "$(dirname "$0")" || exit 1
CWD=$(pwd)

PRGNAM=libShabal
VERSION=${VERSION:-1.4.1}
BUILD=${BUILD:-1}

ARCH=${ARCH:-$(uname -m)}
case "$ARCH" in
    x86_64)  LIBDIRSUFFIX="64" ;;
    *)       LIBDIRSUFFIX=""   ;;
esac

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

set -e

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

# --- sanity --------------------------------------------------------------
[ -f "$CWD/$PRGNAM-$VERSION.tar.gz" ] \
    || { echo "ERROR: $PRGNAM-$VERSION.tar.gz not found in $CWD" >&2; exit 1; }

command -v cargo >/dev/null 2>&1 || { echo "ERROR: cargo not in PATH" >&2; exit 1; }
command -v gcc >/dev/null 2>&1 || { echo "ERROR: gcc not in PATH" >&2; exit 1; }
command -v strip >/dev/null 2>&1 || { echo "ERROR: strip not in PATH" >&2; exit 1; }

# --- unpack --------------------------------------------------------------
rm -rf "$PKG" "$TMP/$PRGNAM-$VERSION"
mkdir -p "$TMP" "$PKG" "$OUTPUT"

cd "$TMP"
tar xf "$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 {} \;

# --- hardening flags -----------------------------------------------------
# Two sides to this build:
#
# C side (compiled by build.rs via the cc crate):
#   -O2 -fPIC -fstack-protector-strong -fstack-clash-protection
#   -fstrict-flex-arrays=3 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=3
#   -fcf-protection=full
#   The cc crate reads CFLAGS from the environment and appends its own
#   toolchain flags. Explicit flags are used instead of -fhardened
#   because -fhardened's link-time expansion includes -pie, which is
#   wrong for a shared object.
#
# Rust side (rustc):
#   -C relocation-model=pic
#   -C link-arg=-Wl,-z,relro,-z,now
#   -C link-arg=-Wl,-z,noexecstack
#   -C link-arg=-Wl,-z,ibt -C link-arg=-Wl,-z,shstk
#   -C force-frame-pointers=yes
#   Stable Rust has no -Z stack-protector and no -Z cf-protection path.
#   FORTIFY cannot fire on Rust-origin calls because rustc does not go
#   through a C preprocessor. Both are documented exceptions in
#   AUDIT.TXT.
export CFLAGS="-O2 -fPIC -fstack-protector-strong -fstack-clash-protection \
  -fstrict-flex-arrays=3 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=3 \
  -fcf-protection=full"
export CXXFLAGS="$CFLAGS"
export LDFLAGS="-Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack -Wl,-z,ibt -Wl,-z,shstk"
export RUSTFLAGS="-C relocation-model=pic \
  -C link-arg=-Wl,-z,relro,-z,now \
  -C link-arg=-Wl,-z,noexecstack \
  -C link-arg=-Wl,-z,force-ibt \
  -C link-arg=-Wl,-z,shstk \
  -C force-frame-pointers=yes"

# --- build ---------------------------------------------------------------
if [ -f Cargo.lock ]; then
    cargo build --release --locked
else
    cargo build --release
fi

# --- install -------------------------------------------------------------
SO=$(find target/release -maxdepth 1 -type f -name '*.so' -print -quit)
if [ -z "$SO" ]; then
    echo "ERROR: cargo build produced no .so in target/release" >&2
    echo "Contents of target/release:" >&2
    ls -la target/release/ >&2 || true
    exit 1
fi

# The audit expects the installed file to be named libshabal.so. If the
# crate name differs, the cargo output name differs too; normalize here.
mkdir -p "$PKG/usr/lib${LIBDIRSUFFIX}"
install -m 755 "$SO" "$PKG/usr/lib${LIBDIRSUFFIX}/libshabal.so"

# --- strip ---------------------------------------------------------------
strip --strip-unneeded "$PKG/usr/lib${LIBDIRSUFFIX}/libshabal.so" || true

# --- docs ----------------------------------------------------------------
mkdir -p "$PKG/usr/doc/$PRGNAM-$VERSION"
for f in README* COPYING* LICENSE* ChangeLog* AUTHORS* NEWS*; do
    [ -e "$f" ] && cp -a "$f" "$PKG/usr/doc/$PRGNAM-$VERSION/"
done
cat "$CWD/$PRGNAM.SlackBuild" > "$PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM.SlackBuild"

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

# --- package -------------------------------------------------------------
cd "$PKG"
/sbin/makepkg -l y -c n "$OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.${PKGTYPE:-txz}"

# --- verify --------------------------------------------------------------
SO="$PKG/usr/lib${LIBDIRSUFFIX}/libshabal.so"
echo ""
echo ">>> Hardening verification for $(basename "$SO")"
echo "--- NEEDED ---"
readelf -d "$SO" | grep NEEDED || true
echo "--- RELRO / BIND_NOW / exec-stack ---"
readelf -lW "$SO" | grep -E 'GNU_RELRO|GNU_STACK' || true
readelf -dW "$SO" | grep BIND_NOW || true
echo "--- CET ---"
readelf -nW "$SO" | grep -E 'IBT|SHSTK' || echo "  (none)"
echo "--- stack canary ---"
readelf -sW "$SO" | grep __stack_chk_fail || echo "  (none)"
echo "--- FORTIFY ---"
readelf -sW "$SO" | grep '_chk@' || echo "  (none)"
echo "--- compiler ---"
readelf -p .comment "$SO" 2>/dev/null | grep -E 'GCC|clang|rustc' || true
echo ""

echo "Package built: $OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.${PKGTYPE:-txz}"
