#!/bin/bash
# Voxis "Iron Hand" Protocol - Manual Linker Override
set -e

# --- 1. TARGET ACQUISITION ---
BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$BASE_DIR"

CACHE_DIR="/tmp/nip-arm64-cache"
OUTPUT_DIR="build/arm64"
TARGET="$OUTPUT_DIR/nip"

VENDOR="$(realpath ../../core/nexus/vendor)"
ZSTD_PATH="$VENDOR/zstd-1.5.5/lib"
LIBRE_PATH="$VENDOR/libressl-3.8.2"

LIBRE_SSL_LIB="$LIBRE_PATH/ssl/.libs"
LIBRE_CRYPTO_LIB="$LIBRE_PATH/crypto/.libs"
LIBRE_TLS_LIB="$LIBRE_PATH/tls/.libs"

mkdir -p "$OUTPUT_DIR"

echo "🔨 [IRON HAND] Locating debris..."

# Gather all object files from the cache
# We filter out any potential garbage, ensuring only .o files
OBJECTS=$(find "$CACHE_DIR" -name "*.o" 2>/dev/null | tr '\n' ' ')

if [ -z "$OBJECTS" ]; then
    echo "❌ ERROR: No object files found in $CACHE_DIR. Did you run the compile step?"
    exit 1
fi

OBJ_COUNT=$(echo "$OBJECTS" | wc -w)
echo "   Found $OBJ_COUNT object files"

echo "🔗 [IRON HAND] Linking Sovereign Artifact (with Shim)..."

# 2.1: Validate Shim exists
SHIM_OBJ="$BASE_DIR/src/openssl_shim.o"
if [ ! -f "$SHIM_OBJ" ]; then
    echo "❌ Missing Shim: $SHIM_OBJ"
    echo "   Run: cd src && aarch64-linux-gnu-gcc -c openssl_shim.c -o openssl_shim.o -I../../nexus/vendor/libressl-3.8.2/include -O2"
    exit 1
fi

# --- 2. THE WELD ---
# We invoke the cross-compiler directly as the linker.
# We feed it every single object file Nim created + our shim.

aarch64-linux-gnu-gcc \
    $OBJECTS \
    "$SHIM_OBJ" \
    -o "$TARGET" \
    -L"$ZSTD_PATH" \
    -L"$LIBRE_SSL_LIB" \
    -L"$LIBRE_CRYPTO_LIB" \
    -L"$LIBRE_TLS_LIB" \
    -static \
    -lpthread \
    -lssl -lcrypto -ltls \
    -lzstd \
    -ldl -lm -lrt -lresolv \
    -Wl,-z,muldefs \
    -Wl,-O1 -Wl,--sort-common -Wl,--as-needed -Wl,-z,relro -Wl,-z,now

# --- 3. VERIFICATION ---
echo ""
if [ -f "$TARGET" ]; then
    echo "✅ [SUCCESS] Binary forged at: $TARGET"
    echo ""
    ls -lh "$TARGET"
    file "$TARGET"
    echo ""
    
    echo "🔎 Checking linkage type..."
    # If static, 'ldd' should say "not a dynamic executable"
    if ldd "$TARGET" 2>&1 | grep -q "not a dynamic executable"; then
        echo "   ✅ Structure: STATIC"
    else
        echo "   ⚠️  Structure: DYNAMIC"
        ldd "$TARGET" | head -n 5
    fi
    
    echo ""
    echo "🔎 Checking for libcrypto.so references..."
    if strings "$TARGET" | grep -q "libcrypto.so"; then
        echo "   ⚠️  Found dlopen references (may still work if --dynlibOverride worked)"
    else
        echo "   ✅ No libcrypto.so dlopen references"
    fi
else
    echo "❌ [FAILURE] Linker command finished but no binary produced."
    exit 1
fi
