#!/bin/bash
set -e

# This script builds standalone binaries for the Cortex Agent Node
# using Docker Multi-Arch BuildX and PyInstaller.

echo "🏗️ Setting up builder..."
cd "$(dirname "$0")/../.."

# Default to current machine's architecture
ARCH_AMD64=false
ARCH_ARM64=false
BUILD_ALL=false

for arg in "$@"; do
    if [ "$arg" == "--all" ]; then
        BUILD_ALL=true
        ARCH_AMD64=true
        ARCH_ARM64=true
    fi
    if [ "$arg" == "--arch=amd64" ]; then
        ARCH_AMD64=true
    fi
    if [ "$arg" == "--arch=arm64" ]; then
        ARCH_ARM64=true
    fi
done

# If no arch is specified, use current host arch
if [ "$BUILD_ALL" = false ] && [ "$ARCH_AMD64" = false ] && [ "$ARCH_ARM64" = false ]; then
    CURRENT_ARCH=$(uname -m)
    if [ "$CURRENT_ARCH" == "x86_64" ]; then
        ARCH_AMD64=true
        echo "Detected x86_64, building only AMD64 binary..."
    elif [ "$CURRENT_ARCH" == "aarch64" ] || [ "$CURRENT_ARCH" == "arm64" ]; then
        ARCH_ARM64=true
        echo "Detected ARM64, building only ARM64 binary..."
    else
        echo "Unknown architecture $CURRENT_ARCH, building both..."
        ARCH_AMD64=true
        ARCH_ARM64=true
    fi
fi

# Ensure buildx is available
docker buildx create --use --name cortex-builder || true

if [ "$ARCH_AMD64" = true ]; then
    echo "🔨 Building Linux AMD64 Binary..."
    docker buildx build \
      --platform linux/amd64 \
      --build-arg ARCH=amd64 \
      -f agent-node/Dockerfile.binary \
      --output type=local,dest=agent-node/dist/linux_amd64 \
      .
fi

if [ "$ARCH_ARM64" = true ]; then
    echo "🔨 Building Linux ARM64 Binary..."
    docker buildx build \
      --platform linux/arm64 \
      --build-arg ARCH=arm64 \
      -f agent-node/Dockerfile.binary \
      --output type=local,dest=agent-node/dist/linux_arm64 \
      .
fi

echo "✅ Build complete! Binaries are in agent-node/dist/"
chmod +x agent-node/dist/*/cortex-agent || true
