#!/usr/bin/env sh
set -eu

# Get system information
ARCH=$(uname -m)
OS=$(uname -s)

# Determine if we need to cross-compile
NEED_CROSS_COMPILE=false
if [ "$OS" = "Darwin" ]; then
    # Always need cross-compilation on macOS
    NEED_CROSS_COMPILE=true
elif [ "$ARCH" != "x86_64" ]; then
    # Need cross-compilation on non-x86_64 Linux
    NEED_CROSS_COMPILE=true
fi

# Handle cross-compilation if needed
if [ "$NEED_CROSS_COMPILE" = true ]; then
    echo "Cross-compilation required for x86_64-unknown-linux-gnu target"

    # Check if cross-compiler is available
    if ! command -v x86_64-linux-gnu-gcc >/dev/null 2>&1; then
        if [ "$OS" = "Darwin" ]; then
            echo "Installing cross compile toolchain"
            brew tap messense/macos-cross-toolchains
            brew install x86_64-unknown-linux-gnu
        else
            echo "x86_64-linux-gnu-gcc not found. Please install the appropriate cross-compiler."
            exit 1
        fi
    fi

    # Set cross-compiler
    export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER=x86_64-linux-gnu-gcc
    TARGET_FLAG="--target x86_64-unknown-linux-gnu"
else
    echo "Native compilation on x86_64 Linux, no cross-compilation needed"
    TARGET_FLAG=""
fi

# Build the project
cargo build --release --package mls_validation_service --features test-utils $TARGET_FLAG

TARGET_DIR="$(cargo metadata --format-version 1 --no-deps | jq -r '.target_directory')"
# Copy the binary to the cache directory
mkdir -p .cache
if [ -n "$TARGET_FLAG" ]; then
    cp -f "${TARGET_DIR}"/x86_64-unknown-linux-gnu/release/mls-validation-service ./.cache/mls-validation-service
else
    cp -f "${TARGET_DIR}"/release/mls-validation-service ./.cache/mls-validation-service
fi

# Build the Docker image
docker build --platform=linux/amd64 -t xmtp/mls-validation-service:latest -f ./dev/validation_service/local.Dockerfile .
