#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
RUNTIME="${SPOON_AGENT_CONTAINER_RUNTIME:-}"
BUILD_SHA="${SPOON_BUILD_SHA:-$(git -C "$ROOT_DIR" rev-parse --short=12 HEAD 2>/dev/null || printf development)}"
BUILD_CREATED_AT="${SPOON_BUILD_CREATED_AT:-$(date -u +%Y-%m-%dT%H:%M:%SZ)}"

if [[ -z "$RUNTIME" ]]; then
  if command -v podman >/dev/null 2>&1; then
    RUNTIME=podman
  elif command -v docker >/dev/null 2>&1; then
    RUNTIME=docker
  else
    printf 'build-agent-images: podman or docker is required.\n' >&2
    exit 1
  fi
fi

"$RUNTIME" build \
  --build-arg "SPOON_BUILD_SHA=$BUILD_SHA" \
  --build-arg "SPOON_BUILD_CREATED_AT=$BUILD_CREATED_AT" \
  -f "$ROOT_DIR/docker/agent-worker.Dockerfile" \
  -t spoon-agent-worker:latest \
  "$ROOT_DIR"
"$RUNTIME" build -f "$ROOT_DIR/docker/agent-job.Dockerfile" -t spoon-agent-job:latest "$ROOT_DIR"
