#!/bin/bash
#
# This script builds, tests, and prepares the mcp-bridge binary for deployment.

set -e

# --- Configuration ---
BINARY_NAME="mcp-bridge"
SRC_PATH="./src" # Build the package in the src directory
DIST_DIR="./dist"
VERSION=$(git describe --tags --always --dirty 2>/dev/null || echo "dev")
BUILD_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
COMMIT_HASH=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")

# Define target platforms (OS/ARCH) that match install.sh
TARGETS="linux/amd64 linux/arm64 darwin/amd64 darwin/arm64"

# --- Setup ---
mkdir -p ${DIST_DIR}

# --- Test ---
echo "--- Running Tests ---"
# This command will run tests in all subdirectories.
go test ./... || { echo "Tests failed"; exit 1; }
echo "--- Tests Finished ---"
echo ""

# --- Build ---
echo "--- Building Binaries ---"
# Clean the distribution directory
rm -f ${DIST_DIR}/*

for TARGET in $TARGETS; do
    # Split the target into OS and ARCH
    GOOS=$(echo $TARGET | cut -f1 -d'/')
    GOARCH=$(echo $TARGET | cut -f2 -d'/')
    OUTPUT_NAME="${DIST_DIR}/${BINARY_NAME}-${GOOS}-${GOARCH}"

    echo "Building for ${GOOS}/${GOARCH}..."
    # Set environment variables and build with version information
    env GOOS=$GOOS GOARCH=$GOARCH go build -o $OUTPUT_NAME \
        -ldflags "-X main.Version=${VERSION} -X main.BuildTime=${BUILD_TIME} -X main.CommitHash=${COMMIT_HASH}" \
        $SRC_PATH

    if [ $? -eq 0 ]; then
        echo "Successfully built ${OUTPUT_NAME}"
        # Create a checksum file for verification
        if command -v sha256sum >/dev/null 2>&1; then
            sha256sum $OUTPUT_NAME > ${OUTPUT_NAME}.sha256
        elif command -v shasum >/dev/null 2>&1; then
            shasum -a 256 $OUTPUT_NAME > ${OUTPUT_NAME}.sha256
        fi
    else
        echo "Error building for ${GOOS}/${GOARCH}"
        exit 1
    fi
done

# Create a symbolic link for the native platform
NATIVE_OS=$(uname -s | tr '[:upper:]' '[:lower:]')
NATIVE_ARCH=$(uname -m)
if [ "$NATIVE_ARCH" = "x86_64" ]; then
    NATIVE_ARCH="amd64"
elif [ "$NATIVE_ARCH" = "aarch64" ] || [ "$NATIVE_ARCH" = "arm64" ]; then
    NATIVE_ARCH="arm64"
fi

NATIVE_BINARY="${DIST_DIR}/${BINARY_NAME}-${NATIVE_OS}-${NATIVE_ARCH}"
if [ -f "$NATIVE_BINARY" ]; then
    ln -sf $(basename $NATIVE_BINARY) ${DIST_DIR}/${BINARY_NAME}
    echo "Created symbolic link for native platform: ${DIST_DIR}/${BINARY_NAME}"
fi

echo "--- Build Finished ---"
echo ""

# --- Deploy ---
echo "--- Staging for Deploy ---"
echo "Adding binaries to Git..."
git add ${DIST_DIR}

echo ""
echo "Binaries are staged for commit."
echo "To complete the deployment, please run:"
echo "  git commit -m \"build: Compile binaries for version ${VERSION}\""
echo "  git push"
echo ""
echo "Build script finished."
