#!/bin/bash
# Voxis Static Build Protocol (GCC Edition)
# Cross-compile nip for ARM64 using GNU toolchain

set -e

echo "🛡️  [VOXIS] ARM64 Static Build (GCC Cross-Compile)"
echo "=========================================================="
echo ""

# 1. Define Paths
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ZSTD_LIB_PATH="$SCRIPT_DIR/../nexus/vendor/zstd-1.5.5/lib"
ZSTD_INC_PATH="$SCRIPT_DIR/../nexus/vendor/zstd-1.5.5/lib"
SSL_LIB_PATH="$SCRIPT_DIR/../nexus/vendor/libressl-3.8.2"
SSL_INC_PATH="$SCRIPT_DIR/../nexus/vendor/libressl-3.8.2/include"
OUTPUT_DIR="$SCRIPT_DIR/build/arm64"

mkdir -p "$OUTPUT_DIR"

echo "📦 Zstd Library: $ZSTD_LIB_PATH/libzstd.a"
echo "📦 LibreSSL Libraries: $SSL_LIB_PATH/{crypto,ssl,tls}/.libs/*.a"
echo "📂 Output: $OUTPUT_DIR/nip"
echo ""

# 2. Verify libzstd.a exists and is ARM64
if [ ! -f "$ZSTD_LIB_PATH/libzstd.a" ]; then
    echo "❌ Error: libzstd.a not found at $ZSTD_LIB_PATH"
    exit 1
fi

if [ ! -f "$SSL_LIB_PATH/crypto/.libs/libcrypto.a" ]; then
    echo "❌ Error: libcrypto.a not found at $SSL_LIB_PATH/crypto/.libs/"
    exit 1
fi

echo "✅ Static libraries verified"
echo ""

# 3. Clean previous build
rm -f "$OUTPUT_DIR/nip"
rm -rf ~/.cache/nim/nip_*
echo "🧹 Cleaned previous builds"
echo ""

# 4. Compile with GCC cross-compiler
echo "🔨 Compiling nip for ARM64..."
echo "   This may take a few minutes..."
echo ""

# Put wrapper in PATH
export PATH="/tmp/gcc-wrapper-bin:$PATH"

nim c \
    --skipProjCfg \
    --nimcache:/tmp/nip-arm64-cache \
    -d:release \
    -d:danger \
    -d:ssl \
    -d:nimcrypto_disable_neon \
    -d:nimcrypto_no_asm \
    --dynlibOverride:ssl \
    --dynlibOverride:crypto \
    --cpu:arm64 \
    --os:linux \
    --cc:gcc \
    --gcc.exe:aarch64-linux-gnu-gcc \
    --gcc.linkerexe:aarch64-linux-gnu-gcc \
    --passC:"-I$ZSTD_INC_PATH -I$SSL_INC_PATH" \
    --passL:"-L$ZSTD_LIB_PATH -L$SSL_LIB_PATH/ssl/.libs -L$SSL_LIB_PATH/crypto/.libs -L$SSL_LIB_PATH/tls/.libs" \
    --passL:"-static -lssl -lcrypto -ltls -lzstd -lpthread -lm -lresolv" \
    --opt:size \
    --mm:orc \
    --threads:on \
    --out:"$OUTPUT_DIR/nip" \
    src/nip.nim

# 5. Verify output
if [ ! -f "$OUTPUT_DIR/nip" ]; then
    echo ""
    echo "❌ Build failed: binary not produced"
    exit 1
fi

echo ""
echo "✅ Build successful!"
echo ""
echo "📊 Binary info:"
ls -lh "$OUTPUT_DIR/nip"
file "$OUTPUT_DIR/nip"
echo ""

# Check if it's actually ARM64 and static
if file "$OUTPUT_DIR/nip" | grep -q "ARM aarch64"; then
    echo "✅ Architecture: ARM64 (aarch64)"
else
    echo "⚠️  Warning: Binary may not be ARM64"
fi

if file "$OUTPUT_DIR/nip" | grep -q "statically linked"; then
    echo "✅ Linking: Static"
else
    echo "⚠️  Warning: Binary may not be statically linked"
fi

echo ""
echo "🎯 Output: $OUTPUT_DIR/nip"
