#!/bin/bash
# Build mcplocal (HTTP-only) Docker image and push to Gitea container registry.
#
# Usage:
#   ./build-mcplocal.sh [tag]                    # Build for native arch
#   ./build-mcplocal.sh [tag] --platform linux/amd64
#   ./build-mcplocal.sh [tag] --multi-arch
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
cd "$PROJECT_ROOT"

# Load .env for GITEA_TOKEN
if [ -f .env ]; then
  set -a; source .env; set +a
fi

# Push directly to internal address (external proxy has body size limit)
REGISTRY="10.0.0.194:3012"
IMAGE="mcplocal"
TAG="${1:-latest}"

PLATFORM=""
MULTI_ARCH=false
shift 2>/dev/null || true
while [[ $# -gt 0 ]]; do
  case "$1" in
    --platform)
      PLATFORM="$2"
      shift 2
      ;;
    --multi-arch)
      MULTI_ARCH=true
      shift
      ;;
    *)
      shift
      ;;
  esac
done

if [ "$MULTI_ARCH" = true ]; then
  echo "==> Building multi-arch $IMAGE image (linux/amd64 + linux/arm64)..."
  podman build --platform linux/amd64,linux/arm64 \
    --manifest "$IMAGE:$TAG" -f deploy/Dockerfile.mcplocal .

  echo "==> Tagging manifest as $REGISTRY/michal/$IMAGE:$TAG..."
  podman tag "$IMAGE:$TAG" "$REGISTRY/michal/$IMAGE:$TAG"

  echo "==> Logging in to $REGISTRY..."
  podman login --tls-verify=false -u michal -p "$GITEA_TOKEN" "$REGISTRY"

  echo "==> Pushing manifest to $REGISTRY/michal/$IMAGE:$TAG..."
  podman manifest push --tls-verify=false --all \
    "$REGISTRY/michal/$IMAGE:$TAG" "docker://$REGISTRY/michal/$IMAGE:$TAG"
else
  PLATFORM_FLAG=""
  if [ -n "$PLATFORM" ]; then
    PLATFORM_FLAG="--platform $PLATFORM"
    echo "==> Building $IMAGE image for $PLATFORM..."
  else
    echo "==> Building $IMAGE image (native arch)..."
  fi

  podman build $PLATFORM_FLAG -t "$IMAGE:$TAG" -f deploy/Dockerfile.mcplocal .

  echo "==> Tagging as $REGISTRY/michal/$IMAGE:$TAG..."
  podman tag "$IMAGE:$TAG" "$REGISTRY/michal/$IMAGE:$TAG"

  echo "==> Logging in to $REGISTRY..."
  podman login --tls-verify=false -u michal -p "$GITEA_TOKEN" "$REGISTRY"

  echo "==> Pushing to $REGISTRY/michal/$IMAGE:$TAG..."
  podman push --tls-verify=false "$REGISTRY/michal/$IMAGE:$TAG"
fi

# Ensure package is linked to the repository
source "$SCRIPT_DIR/link-package.sh"
link_package "container" "$IMAGE"

echo "==> Done!"
echo "    Image: $REGISTRY/michal/$IMAGE:$TAG"
