#!/bin/bash
# NIP Static Build Script - "Weihnachtsmann" 🎅✨
# Builds a fully static, portable binary for minimal deployment
set -e

echo "🎅 Building NIP v0.2.0 'Weihnachtsmann' - Static 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 ""

# Check for musl-gcc (optional but recommended for smaller binaries)
if command -v musl-gcc &> /dev/null; then
    echo "✅ musl-gcc found - will use for optimal static linking"
    USE_MUSL=true
else
    echo "ℹ️  musl-gcc not found - using glibc (larger binary)"
    echo "   Install musl-tools for smaller binaries: sudo apt install musl-tools"
    USE_MUSL=false
fi
echo ""

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

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

if [ "$USE_MUSL" = true ]; then
    # Build with musl for smallest possible binary
    nim c \
        --define:static \
        --define:release \
        --define:danger \
        --opt:speed \
        --mm:orc \
        --threads:on \
        --passC:-flto \
        --passL:-flto \
        --passL:-static \
        --passL:-s \
        --gcc.exe:musl-gcc \
        --gcc.linkerexe:musl-gcc \
        --hints:off \
        --warnings:off \
        --out:nip-static \
        nip.nim
else
    # Build with glibc (larger but more compatible)
    nim c \
        --define:static \
        --define:release \
        --define:danger \
        --opt:speed \
        --mm:orc \
        --threads:on \
        --passC:-flto \
        --passL:-flto \
        --passL:-static \
        --passL:-static-libgcc \
        --passL:-s \
        --hints:off \
        --warnings:off \
        --out:nip-static \
        nip.nim
fi

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

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

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

# Show file size comparison
if [ -f "nip_release" ]; then
    echo "📏 Size Comparison:"
    echo "   Dynamic binary: $(ls -lh nip_release | awk '{print $5}')"
    echo "   Static binary:  $(ls -lh nip-static | awk '{print $5}')"
    echo ""
fi

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

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

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

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

## Minimal Install Philosophy

This is a **fully static binary** designed for the ultimate minimal-to-complete workflow:

1. Boot a tiny netinst image (50-100MB)
2. Install NIP (this single ~5MB binary)
3. Build your perfect system from scratch in minutes

## Quick Start

```bash
# Install (as root)
sudo cp nip /usr/local/bin/nip
sudo chmod +x /usr/local/bin/nip

# Initialize
sudo nip setup

# Start using
nip graft aur firefox +wayland -X
nip graft nix neovim +lua +python
nip install --build-from-source nginx +http3
```

## Features

- ✅ Fully static binary (no dependencies)
- ✅ Works on any Linux with kernel 4.19+
- ✅ Access to 100,000+ packages (Nix, AUR, Gentoo, PKGSRC, Pacman)
- ✅ USE flags for full customization
- ✅ Fast deployment (5-15 minutes to desktop)

## Documentation

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

## License

Dual licensed under EUPL-1.2 and ACUL
EOF

# Create ultra-minimal install script
cat > "$RELEASE_DIR/install.sh" << 'EOF'
#!/bin/bash
# NIP Minimal Installation Script
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'"
cp nip /usr/local/bin/nip
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 "🎉 Static build complete!"
echo ""
echo "📋 Build Summary:"
echo "   Binary: nip-static"
if [ "$FULLY_STATIC" = true ]; then
    echo "   Status: ✅ Fully static (no dependencies)"
else
    echo "   Status: ⚠️  Has some dynamic dependencies"
fi
echo "   Size: $(ls -lh nip-static | awk '{print $5}')"
if [ "$USE_MUSL" = true ]; then
    echo "   Libc: musl (optimal)"
else
    echo "   Libc: glibc (compatible)"
fi
echo ""
echo "📦 Deployment Package:"
echo "   Directory: $RELEASE_DIR/"
echo "   Tarball: $RELEASE_DIR.tar.gz"
echo ""
echo "🎅 Ready for Christmas release! ✨"
