#!/bin/bash
# Build and push rdev images to GitHub Container Registry
#
# Usage:
#   ./build-push.sh                    # Build all images with 'latest' tag
#   ./build-push.sh v0.4.0             # Build all images with version tag
#   ./build-push.sh v0.4.0 claudebox   # Build only claudebox image
#   ./build-push.sh v0.4.0 api         # Build only api image
#   ./build-push.sh v0.4.0 worker      # Build only worker image

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Image configuration
REGISTRY="ghcr.io/orchard9"
VERSION="${1:-latest}"
TARGET="${2:-all}"

cd "$PROJECT_ROOT"

build_claudebox() {
  local IMAGE_TAG="$REGISTRY/rdev-claudebox:$VERSION"
  echo "Building claudebox image..."
  echo "Image: $IMAGE_TAG"
  echo ""

  # Build the image for linux/amd64 (k3s nodes are amd64)
  docker build --platform linux/amd64 \
    -t "$IMAGE_TAG" \
    -t "$REGISTRY/rdev-claudebox:latest" \
    -f Dockerfile \
    .

  echo ""
  echo "Pushing claudebox to GitHub Container Registry..."
  docker push "$IMAGE_TAG"
  docker push "$REGISTRY/rdev-claudebox:latest"

  echo "Pushed: $IMAGE_TAG"
}

build_api() {
  local IMAGE_TAG="$REGISTRY/rdev-api:$VERSION"
  echo "Building rdev-api image..."
  echo "Image: $IMAGE_TAG"
  echo ""

  # Build the image for linux/amd64
  docker build --platform linux/amd64 \
    -t "$IMAGE_TAG" \
    -t "$REGISTRY/rdev-api:latest" \
    -f Dockerfile.api \
    .

  echo ""
  echo "Pushing rdev-api to GitHub Container Registry..."
  docker push "$IMAGE_TAG"
  docker push "$REGISTRY/rdev-api:latest"

  echo "Pushed: $IMAGE_TAG"
}

build_worker() {
  local IMAGE_TAG="$REGISTRY/rdev-worker:$VERSION"
  echo "Building rdev-worker image..."
  echo "Image: $IMAGE_TAG"
  echo ""

  # Build the image for linux/amd64
  docker build --platform linux/amd64 \
    -t "$IMAGE_TAG" \
    -t "$REGISTRY/rdev-worker:latest" \
    -f Dockerfile.worker \
    .

  echo ""
  echo "Pushing rdev-worker to GitHub Container Registry..."
  docker push "$IMAGE_TAG"
  docker push "$REGISTRY/rdev-worker:latest"

  echo "Pushed: $IMAGE_TAG"
}

case "$TARGET" in
  claudebox)
    build_claudebox
    ;;
  api)
    build_api
    ;;
  worker)
    build_worker
    ;;
  all)
    build_claudebox
    echo ""
    echo "---"
    echo ""
    build_api
    echo ""
    echo "---"
    echo ""
    build_worker
    ;;
  *)
    echo "Unknown target: $TARGET"
    echo "Usage: $0 [version] [claudebox|api|worker|all]"
    exit 1
    ;;
esac

echo ""
echo "Done!"
echo ""
echo "To deploy, run:"
echo "  export KUBECONFIG=~/.kube/orchard9-k3sf.yaml"
echo "  kubectl apply -k deployments/k8s/base"
