#!/bin/bash
# CUSTOM_BUILD_HARDENED
export CFLAGS="${CFLAGS:--O2} -fhardened -fPIC"
export CXXFLAGS="${CXXFLAGS:--O2} -fhardened -fPIC"
export LDFLAGS="${LDFLAGS:-} -Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack -Wl,-z,ibt -Wl,-z,shstk"

# AMOS build script for libjnidispatch
# Minimal build: only the .so. No jar, no bundled libffi.
#
# Built from JNA 5.14.0 because that is the release whose native
# version is 7.0.0, matching the VERSION_NATIVE constant compiled
# into anne-node.jar. JNA 5.19.1 would produce 7.0.3 and fail the
# runtime handshake.
#
# 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=libjnidispatch
VERSION=${VERSION:-5.14.0}
BUILD=${BUILD:-1}
PKGTYPE=${PKGTYPE:-txz}

# The native version string compiled into anne-node.jar's
# com.sun.jna.Version class. Confirmed by extracting Version.class
# from the jar: public static final String VERSION_NATIVE = "7.0.0";
#
# JNA versions the native library separately from the project. The
# native version advances only when the JNI interface changes. For
# 5.14.0 it is 7.0.0; for 5.15.0 it was 7.0.1; for 5.16.0 it was
# 7.0.3; for 5.19.1 it is 7.0.3. The handshake is an exact string
# comparison, so the value must match what the jar expects.
JNA_NATIVE_VERSION="7.0.0"

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

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

JNA_TOPDIR=$PWD
JAVA_HOME=${JAVA_HOME:-/usr/lib64/java}

# ---------------------------------------------------------------------------
# Sanity: system libffi must be present. Slackware's l/libffi ships
# /usr/include/ffi.h and /usr/lib64/libffi.so. If either is missing,
# stop with a clear message rather than failing later in the link.
# ---------------------------------------------------------------------------
[ -r /usr/include/ffi.h ] \
    || { echo "ERROR: /usr/include/ffi.h not found; install Slackware's l/libffi" >&2; exit 1; }
[ -r /usr/include/ffitarget.h ] \
    || { echo "ERROR: /usr/include/ffitarget.h not found; install Slackware's l/libffi" >&2; exit 1; }

# ---------------------------------------------------------------------------
# Verify that this source tree actually declares the expected native
# version. build.xml defines jni.major/jni.minor/jni.revision, and the
# build substitutes them into Version.java's VERSION_NATIVE constant.
# If the source tree has drifted, fail early rather than building a
# library whose version string will not match the jar.
# ---------------------------------------------------------------------------
BUILD_XML_NATIVE=$(
    grep -oP 'name="jni\.major" value="\K[0-9]+' build.xml 2>/dev/null | head -1
).$(
    grep -oP 'name="jni\.minor" value="\K[0-9]+' build.xml 2>/dev/null | head -1
).$(
    grep -oP 'name="jni\.revision" value="\K[0-9]+' build.xml 2>/dev/null | head -1
)

if [ -z "$BUILD_XML_NATIVE" ] || [ "$BUILD_XML_NATIVE" = ".." ]; then
    echo "WARNING: could not read jni.version from build.xml; assuming $JNA_NATIVE_VERSION" >&2
elif [ "$BUILD_XML_NATIVE" != "$JNA_NATIVE_VERSION" ]; then
    echo "ERROR: build.xml declares native version $BUILD_XML_NATIVE," >&2
    echo "       but anne-node.jar expects $JNA_NATIVE_VERSION." >&2
    echo "       Wrong JNA source tree. Use the release that produces $JNA_NATIVE_VERSION." >&2
    exit 1
fi

# ---------------------------------------------------------------------------
# HARDENING FLAGS
# ---------------------------------------------------------------------------
HARDEN_CFLAGS="-O2 -fPIC -fstack-protector-strong -fstack-clash-protection -fstrict-flex-arrays=3 -fcf-protection=full -DNO_JAWT"
HARDEN_LDFLAGS="-shared -Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack -Wl,-z,ibt -Wl,-z,shstk"

# ---------------------------------------------------------------------------
# JNA native version macro. Sourced from the JNA_NATIVE_VERSION set
# above, which is what anne-node.jar's VERSION_NATIVE constant holds.
# ---------------------------------------------------------------------------
VERSION_DEF='-DJNA_JNI_VERSION="'"$JNA_NATIVE_VERSION"'"'

# ---------------------------------------------------------------------------
# Step 1: generate JNI headers from the Java sources.
# ---------------------------------------------------------------------------
mkdir -p build/classes build/headers build/native build/native-libs
find src/com/sun/jna -name '*.java' > sources.txt
javac -d build/classes -h build/headers -encoding UTF-8 @sources.txt
rm sources.txt

# ---------------------------------------------------------------------------
# Step 2: compile the two native sources.
# ---------------------------------------------------------------------------
cd native

echo "--- compiling dispatch.c ---"
gcc $CFLAGS $LDFLAGS $HARDEN_CFLAGS $VERSION_DEF \
    -I. \
    -I$JAVA_HOME/include \
    -I$JAVA_HOME/include/linux \
    -I$JNA_TOPDIR/build/headers \
    -c dispatch.c -o "$JNA_TOPDIR/build/native/dispatch.o" \
    || { echo "ERROR: dispatch.c compile failed" >&2; exit 1; }

echo "--- compiling callback.c ---"
gcc $CFLAGS $LDFLAGS $HARDEN_CFLAGS $VERSION_DEF \
    -I. \
    -I$JAVA_HOME/include \
    -I$JAVA_HOME/include/linux \
    -I$JNA_TOPDIR/build/headers \
    -c callback.c -o "$JNA_TOPDIR/build/native/callback.o" \
    || { echo "ERROR: callback.c compile failed" >&2; exit 1; }

cd "$JNA_TOPDIR"

# ---------------------------------------------------------------------------
# Step 3: link.
# ---------------------------------------------------------------------------
echo "--- linking libjnidispatch.so ---"
gcc $CFLAGS $LDFLAGS $HARDEN_LDFLAGS $VERSION_DEF \
    build/native/dispatch.o \
    build/native/callback.o \
    -lffi \
    -o build/native-libs/libjnidispatch.so \
    || { echo "ERROR: link failed" >&2; exit 1; }

NATIVE_LIB="$JNA_TOPDIR/build/native-libs/libjnidispatch.so"

# ---------------------------------------------------------------------------
# Step 4: hardening verification.
# ---------------------------------------------------------------------------
echo "--- hardening check on $NATIVE_LIB ---"
readelf -d "$NATIVE_LIB" | grep -q BIND_NOW \
  || { echo "FAIL: no BIND_NOW"; exit 1; }
readelf -lW "$NATIVE_LIB" | grep -q GNU_RELRO \
  || { echo "FAIL: no GNU_RELRO"; exit 1; }
readelf -lW "$NATIVE_LIB" | grep GNU_STACK | grep -q ' RWE ' \
  && { echo "FAIL: executable stack"; exit 1; } || true
readelf -nW "$NATIVE_LIB" | grep -q IBT \
  || { echo "FAIL: no IBT"; exit 1; }
readelf -nW "$NATIVE_LIB" | grep -q SHSTK \
  || { echo "FAIL: no SHSTK"; exit 1; }
echo "--- hardening check passed ---"

# ---------------------------------------------------------------------------
# Step 5: version string verification.
# ---------------------------------------------------------------------------
echo "--- version string check ---"
readelf -p .rodata "$NATIVE_LIB" 2>/dev/null | grep -q "$JNA_NATIVE_VERSION" \
  || { echo "FAIL: version string $JNA_NATIVE_VERSION not found in $NATIVE_LIB"; exit 1; }
echo "  version string $JNA_NATIVE_VERSION present"
echo "--- version check passed ---"

# ---------------------------------------------------------------------------
# Step 6: install.
# ---------------------------------------------------------------------------
mkdir -p $PKG/usr/lib$LIBDIRSUFFIX
install -m 755 "$NATIVE_LIB" $PKG/usr/lib$LIBDIRSUFFIX/libjnidispatch.so

mkdir -p $PKG/usr/doc/$PRGNAM-$VERSION
cp -a LICENSE README.md $PKG/usr/doc/$PRGNAM-$VERSION 2>/dev/null || true
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
