#!/bin/bash
# Build all Tinqs CI runner images and push to ECR
set -euo pipefail

AWS_REGION="${AWS_REGION:-eu-west-1}"
ACCOUNT_ID="${ACCOUNT_ID:-149751500842}"
ECR_BASE="${ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com"
TAG="${1:-latest}"

echo "=== Logging into ECR ==="
aws ecr get-login-password --region "${AWS_REGION}" | \
  docker login --username AWS --password-stdin "${ECR_BASE}"

# Ensure ECR repos exist
for NAME in tinqs-runner-base tinqs-runner-go tinqs-runner-node tinqs-runner-docker tinqs-runner-deploy tinqs-runner-godot; do
  aws ecr describe-repositories --repository-names "$NAME" --region "$AWS_REGION" 2>/dev/null || \
    aws ecr create-repository --repository-name "$NAME" --region "$AWS_REGION" --no-cli-pager
done

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

# 1. Base (everything depends on this)
echo "=== Building base ==="
docker build -t "${ECR_BASE}/tinqs-runner-base:${TAG}" -t "${ECR_BASE}/tinqs-runner-base:latest" "$SCRIPT_DIR/base"
docker push "${ECR_BASE}/tinqs-runner-base:${TAG}"
docker push "${ECR_BASE}/tinqs-runner-base:latest"

BASE_ARG="--build-arg BASE_IMAGE=${ECR_BASE}/tinqs-runner-base:${TAG}"

# 2. All others in parallel (they only depend on base)
build_and_push() {
  local name=$1
  local dir=$2
  local extra_args="${3:-}"
  echo "=== Building ${name} ==="
  docker build $extra_args -t "${ECR_BASE}/tinqs-runner-${name}:${TAG}" -t "${ECR_BASE}/tinqs-runner-${name}:latest" "$SCRIPT_DIR/$dir"
  docker push "${ECR_BASE}/tinqs-runner-${name}:${TAG}"
  docker push "${ECR_BASE}/tinqs-runner-${name}:latest"
  echo "=== Done ${name} ==="
}

build_and_push "go"     "go"     "$BASE_ARG" &
build_and_push "node"   "node"   "$BASE_ARG" &
build_and_push "deploy" "deploy" "$BASE_ARG" &
build_and_push "docker" "docker" "" &
# godot is optional — uncomment when game CI is ready
# build_and_push "godot" "godot" "$BASE_ARG" &

wait
echo "=== All images built and pushed (tag: ${TAG}) ==="
