#!/bin/bash
set -e

echo "🐧 Building Linux x86_64 binary via Docker (Ubuntu 22.04 base)..."

mkdir -p dist

docker run --rm \
  --platform linux/amd64 \
  -v "$PWD":/work \
  -w /work \
  ubuntu:22.04 \
  bash -c '
    set -e
    export DEBIAN_FRONTEND=noninteractive
    
    # Install Python 3.12 and build tools
    apt-get update -qq
    apt-get install -y -qq software-properties-common
    add-apt-repository -y ppa:deadsnakes/ppa
    apt-get update -qq
    apt-get install -y -qq \
      python3.12 \
      python3.12-venv \
      python3.12-dev \
      binutils \
      gcc \
      g++ \
      make \
      libffi-dev
    
    # Install pip for Python 3.12
    python3.12 -m ensurepip
    python3.12 -m pip install -q --upgrade pip
    python3.12 -m pip install -q pyinstaller
    python3.12 -m pip install -q -r requirements.txt
    
    echo "📝 Patching for frozen build..."
    python3.12 -c "
import sys
with open(\"src/pyhdwallet.py\", \"r\") as f:
    content = f.read()
content = content.replace(
    \"def _require(mod: str, pkg: str) -> None:\\n    try:\",
    \"def _require(mod: str, pkg: str) -> None:\\n    import sys\\n    if getattr(sys, \\\"frozen\\\", False): return\\n    try:\"
)
with open(\"/tmp/pyhdwallet_frozen.py\", \"w\") as f:
    f.write(content)
"
    
    echo "🔧 Building with PyInstaller..."
    python3.12 -m PyInstaller --onefile --name pyhdwallet-linux --clean \
      --collect-all bip_utils \
      --collect-all pgpy \
      --collect-all nacl \
      --collect-all pyzipper \
      --collect-all coincurve \
      --copy-metadata coincurve \
      /tmp/pyhdwallet_frozen.py
    
    echo "✅ Linux binary created (compatible with Ubuntu 22.04+)"
  '

echo ""
echo "Binary location: dist/pyhdwallet-linux"
echo "Size: $(du -h dist/pyhdwallet-linux 2>/dev/null | cut -f1 || echo 'N/A')"
echo "GLIBC: $(docker run --rm --platform linux/amd64 -v "$PWD/dist":/b ubuntu:22.04 ldd /b/pyhdwallet-linux | grep libc.so || echo 'static')"
echo ""
echo "Test it:"
echo "  docker run --rm --platform linux/amd64 -v \"\$PWD/dist\":/bin ubuntu:22.04 /bin/pyhdwallet-linux test"
