#!/bin/bash

# Build all platform binaries for npm package
# Run from gl-cli directory: ./npm/scripts/build-binaries.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
NPM_DIR="$(dirname "$SCRIPT_DIR")"
GL_CLI_DIR="$(dirname "$NPM_DIR")"
BINARIES_DIR="$NPM_DIR/binaries"

echo "Building GitLume CLI binaries..."
echo "Source: $GL_CLI_DIR"
echo "Output: $BINARIES_DIR"
echo ""

# Clean binaries directory
rm -rf "$BINARIES_DIR"
mkdir -p "$BINARIES_DIR"

cd "$GL_CLI_DIR"

# Build for each platform/arch combination
PLATFORMS="darwin linux windows"
ARCHS="amd64 arm64"

for OS in $PLATFORMS; do
  for ARCH in $ARCHS; do
    EXT=""
    if [ "$OS" = "windows" ]; then
      EXT=".exe"
    fi

    OUTPUT="$BINARIES_DIR/gitlume-bin-${OS}-${ARCH}${EXT}"

    echo "Building ${OS}/${ARCH}..."

    CGO_ENABLED=0 GOOS=$OS GOARCH=$ARCH go build \
      -ldflags="-s -w" \
      -o "$OUTPUT" \
      ./cmd/gl

    echo "  -> $(basename $OUTPUT) ($(du -h "$OUTPUT" | cut -f1))"
  done
done

echo ""
echo "All binaries built successfully!"
echo ""
ls -lh "$BINARIES_DIR"
