#!/usr/bin/env bash
# Build the experiment worker and push to ECR with the given tag.
#
# Usage: ./build_and_push.sh <tag>
# Example: ./build_and_push.sh v1

set -euo pipefail

TAG="${1:?Usage: $0 <tag>}"
REGION="us-east-1"
ACCOUNT="103233932089"
REPO="claude-ecs-task-protection-experiment"
REPO_URI="${ACCOUNT}.dkr.ecr.${REGION}.amazonaws.com/${REPO}"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WORKER_DIR="${SCRIPT_DIR}/../worker"

# Isolated docker config so we don't fight a broken credsStore helper
# (amazon-ecr-credential-helper returns "not implemented" on some setups).
# Stores auth tokens inline in a temp config we throw away. We preserve
# the user's current docker context so colima/remote daemons still work.
CURRENT_CONTEXT=$(docker context show 2>/dev/null || echo "default")
CURRENT_HOST=$(docker context inspect "${CURRENT_CONTEXT}" 2>/dev/null \
    | jq -r '.[0].Endpoints.docker.Host' || echo "")
export DOCKER_CONFIG=/tmp/docker-experiment-config
mkdir -p "${DOCKER_CONFIG}"
printf '{"credsStore":"","auths":{},"currentContext":"%s"}\n' "${CURRENT_CONTEXT}" \
    > "${DOCKER_CONFIG}/config.json"
if [[ -n "${CURRENT_HOST}" ]]; then
    export DOCKER_HOST="${CURRENT_HOST}"
fi

aws ecr get-login-password --region "${REGION}" \
    | docker login --username AWS --password-stdin "${ACCOUNT}.dkr.ecr.${REGION}.amazonaws.com"

docker build --platform linux/amd64 -t "${REPO_URI}:${TAG}" -t "${REPO_URI}:latest" "${WORKER_DIR}"
docker push "${REPO_URI}:${TAG}"
docker push "${REPO_URI}:latest"

echo
echo "Pushed ${REPO_URI}:${TAG}"
