#!/usr/bin/env bash
# Build and push hu-agent image to ECR. Use the output as container_image for terraform plan/apply.
# Usage: ./build-and-push-ecr.sh [IMAGE_TAG] [AWS_PROFILE]
# Example (SSO to PFM): aws sso login --profile PFM && ./build-and-push-ecr.sh '' PFM
# With PFM profile, pushes to account 923929101992 (PFM). Otherwise defaults to dev 923929101992.
set -euo pipefail

[[ -n "${2:-}" ]] && export AWS_PROFILE="$2"

AWS_REGION="${AWS_REGION:-us-east-1}"
# PFM account (923929101992) when using profile PFM
AWS_ACCOUNT="${AWS_ACCOUNT:-923929101992}"
ECR_REPO="hu-agent"
IMAGE_TAG="${1:-$(git rev-parse --short HEAD 2>/dev/null || echo 'local')}"

ECR_URI="${AWS_ACCOUNT}.dkr.ecr.${AWS_REGION}.amazonaws.com/${ECR_REPO}:${IMAGE_TAG}"

echo "Building image..."
docker build --platform linux/arm64 -t "$ECR_URI" .

echo "Logging in to ECR..."
aws ecr get-login-password --region "$AWS_REGION" |
  docker login --username AWS --password-stdin "${AWS_ACCOUNT}.dkr.ecr.${AWS_REGION}.amazonaws.com"

# Ensure repo exists (e.g. when pushing to PFM for the first time)
aws ecr describe-repositories --repository-names "$ECR_REPO" --region "$AWS_REGION" &>/dev/null ||
  aws ecr create-repository --repository-name "$ECR_REPO" --region "$AWS_REGION"

echo "Pushing $ECR_URI ..."
docker push "$ECR_URI"

echo ""
echo "Use this for Terraform (dev):"
echo "  terraform -chdir=infrastructure/env/dev plan -var=\"container_image=${ECR_URI}\""
echo "  terraform -chdir=infrastructure/env/dev apply -var=\"container_image=${ECR_URI}\" -auto-approve"
