#!/bin/bash
# NIP Musl Static Build Script -ann" Optimized 🎅✨
# Builds the smallest possible static binary using musl libc
set -e

echo "🎅 Building NIP v0.2.0 'Weihnachtsmann' - Musl Optimized Edition"
echo "=================================================================="
echo ""

# Check if Nim is available
if ! command -v nim &> /dev/null; then
    echo "❌ Error: Nim compiler not found"
    echo "   Please install Nim: https://nim-lang.org/install.html"
    exit 1
fi

# Show Nim version
echo "📋 Nim version: $(nim --version | head -1)"
echo ""

# Find musl-gcc
MUSL_GCC=""
if command -v x86_64-linux-musl-gcc &> /dev/null; then
    MUSL_GCC="x86_64-linux-musl-gcc"
    echo "✅ Found musl-gcc in PATH"
elif [ -f "/opt/cross/x86_64-linux-musl-cross/bin/x86_64-linux-musl-gcc" ]; then
    MUSL_GCC="/opt/cross/x86_64-linux-musl-cross/bin/x86_64-linux-musl-gcc"
    echo "✅ Found musl-gcc at: $MUSL_GCC"
else
    echo "❌ Error: musl-gcc not found"
    echo "   Install musl-cross-bin: yay -S musl-cross-bin"
    exit 1
fi
echo ""

# Clean previous builds
echo "🧹 Cleaning previous builds..."
rm -f nip nip-musl nip-static-musl
echo ""

# Build optimized musl static binary
echo "🔨 Building optimized musl static binary..."
echo "   This may take a few minutes..."
echo ""

nim c \
    --define:static \
    --define:release \
    --define:danger \
    --opt:speed \
    --mm:orc \
    --threads:on \
    --passC:-flto \
    --passL:-flto \
    --passL:-static \
    --passL:-s \
    --passC:-ffunction-sections \
    --passC:-fdata-sections \
    --passL:-Wl,--gc-sections \
    --passC:-march=x86-64-v2 \
    --passC:-mtune=generic \
    --gcc.exe:"$MUSL_GCC" \
    --gcc.linkerexe:"$MUSL_GCC" \
    --hints:off \
    --warnings:off \
    --out:nip-musl \
    nip.nim

if [ ! -f "nip-musl" ]; then
    echo "❌ Build failed!"
    exit 1
fi

# Show binary info
echo ""
echo "✅ Build successful!"
echo ""
echo "📊 Binary Information:"
ls -lh nip-musl
echo ""

# Verify static linking
echo "🔍 Verifying static linking..."
if ldd nip-musl 2>&1 | grep -q "not a dynamic executable"; then
    echo "✅ Binary is fully static (no dynamic dependencies)"
    FULLY_STATIC=true
elif ldd nip-musl 2>&1 | grep -q "statically linked"; then
    echo "✅ Binary is statically linked"
    FULLY_STATIC=true
else
    echo "⚠️  Binary has dynamic dependencies:"
    ldd nip-musl 2>&1 | head -10
    FULLY_STATIC=false
fi
echo ""

# Show file details
echo "📋 File Details:"
file nip-musl
echo ""

# Size comparison
echo "📏 Size Comparison:"
if [ -f "nip-static" ]; then
    GLIBC_SIZE=$(ls -lh nip-static | awk '{print $5}')
    echo "   Glibc static:  $GLIBC_SIZE"
fi
MUSL_SIZE=$(ls -lh nip-musl | awk '{print $5}')
echo "   Musl static:   $MUSL_SIZE"
echo ""

# Test the binary
echo "🧪 Testing binary..."
if ./nip-musl --version > /dev/null 2>&1; then
    echo "✅ Binary test passed"
    ./nip-musl --version 2>/dev/null || echo "   (version check requires root)"
else
    echo "⚠️  Binary test failed (but this is expected without root)"
fi
echo ""

# Check for UPX availability
echo "🔍 Checking for UPX compression..."
if command -v upx &> /dev/null; then
    echo "✅ UPX found - attempting compression..."
    echo ""

    # Create compressed version
    cp nip-musl nip-musl-upx
    upx --best --lzma nip-musl-upx 2>&1 | tail -5

    if [ -f "nip-musl-upx" ]; then
        echo ""
        echo "📦 UPX Compression Results:"
        ORIGINAL=$(ls -lh nip-musl | awk '{print $5}')
        COMPRESSED=$(ls -lh nip-musl-upx | awk '{print $5}')
        echo "   Original:   $ORIGINAL"
        echo "   Compressed: $COMPRESSED"
        echo ""

        # Test compressed binary
        echo "🧪 Testing compressed binary..."
        if ./nip-musl-upx --version > /dev/null 2>&1; then
            echo "✅ Compressed binary works!"
        else
            echo "⚠️  Compressed binary test failed"
        fi
        echo ""
    fi
else
    echo "ℹ️  UPX not found - skipping compression"
    echo "   Install UPX for additional size reduction: sudo pacman -S upx"
    echo ""
fi

# Create deployment package
RELEASE_DIR="nip-v0.2.0-weihnachtsmann-musl-$(uname -s)-$(uname -m)"
echo "📦 Creating deployment package: $RELEASE_DIR"
mkdir -p "$RELEASE_DIR"

# Copy musl binary
cp nip-musl "$RELEASE_DIR/nip"
chmod +x "$RELEASE_DIR/nip"

# Copy compressed version if it exists
if [ -f "nip-musl-upx" ]; then
    cp nip-musl-upx "$RELEASE_DIR/nip-compressed"
    chmod +x "$RELEASE_DIR/nip-compressed"
fi

# Create README
cat > "$RELEASE_DIR/README.md" << 'EOF'
# NIP v0.2.0 "Weihnachtsmann" 🎅✨ - Musl Optimized Edition

## Ultra-Minimal Static Binary

This is a **fully static binary built with musl libc** - the smallest possible NIP binary for maximum portability.

### Features

- ✅ Fully static (no dependencies)
- ✅ Musl libc (smallest possible)
- ✅ Link-Time Optimization (LTO)
- ✅ Section garbage collection
- ✅ Symbol stripping
- ✅ Works on any Linux kernel 4.19+

### Quick Start

```bash
# Install
sudo cp nip /usr/local/bin/nip
sudo chmod +x /usr/local/bin/nip

# Initialize
sudo nip setup

# Start using
nip build nginx +http3
nip graft aur firefox
```

### Compressed Version

If `nip-compressed` is included, it's UPX-compressed for even smaller size:

```bash
sudo cp nip-compressed /usr/local/bin/nip
```

**Trade-off:** Slightly slower startup (~100-200ms decompression)

### Documentation

For full documentation, visit:
https://git.maiwald.work/Nexus/NexusToolKit
EOF

# Create install script
cat > "$RELEASE_DIR/install.sh" << 'EOF'
#!/bin/bash
set -e

if [ "$EUID" -ne 0 ]; then
    echo "⚠️  Please run as root: sudo ./install.sh"
    exit 1
fi

echo "🎅 Installing NIP v0.2.0 'Weihnachtsmann' (Musl Edition)"

# Choose binary
if [ -f "nip-compressed" ]; then
    echo "📦 Found compressed binary - using for smaller size"
    cp nip-compressed /usr/local/bin/nip
else
    cp nip /usr/local/bin/nip
fi

chmod +x /usr/local/bin/nip
echo "✅ Installed to /usr/local/bin/nip"
echo ""
echo "🚀 Run 'nip setup' to initialize"
EOF

chmod +x "$RELEASE_DIR/install.sh"

# Create tarball
echo "📦 Creating release tarball..."
tar -czf "$RELEASE_DIR.tar.gz" "$RELEASE_DIR"
echo "   Created: $RELEASE_DIR.tar.gz"
echo ""

# Final summary
echo "🎉 Musl build complete!"
echo ""
echo "📋 Build Summary:"
echo "   Binary: nip-musl"
if [ "$FULLY_STATIC" = true ]; then
    echo "   Status: ✅ Fully static (no dependencies)"
else
    echo "   Status: ⚠️  Has some dynamic dependencies"
fi
echo "   Size: $(ls -lh nip-musl | awk '{print $5}')"
echo "   Libc: musl (optimal)"
echo ""
echo "📦 Deployment Package:"
echo "   Directory: $RELEASE_DIR/"
echo "   Tarball: $RELEASE_DIR.tar.gz"
echo ""
echo "🎅 Musl optimized build ready! ✨"
