#!/bin/bash
set -euo pipefail

# =============================================================================
# build-helix-base-images.sh
# -----------------------------------------------------------------------------
# Builds and publishes the PHP base images required by the new Helix (Odenza)
# application images, so their Dockerfiles can resolve `FROM .../tbi-php-XX`.
#
# The Helix app Dockerfiles reference these base images:
#   tbi-hlx-dynamic-path         FROM .../tbi-php-85:latest   (NEW)
#   tbi-hlx-whitelabel-frontend  FROM .../tbi-php-85:latest   (NEW)
#   tbi-rlv-helix-bridge         FROM .../tbi-php-85:latest   (NEW)
#   tbi-legacy-hotels-service    FROM .../tbi-php-81:latest   (NEW)
#   tbi-hlx-booking-path         FROM .../tbi-php-73:latest   (already in ECR)
#
# Source Dockerfiles for the base images:
#   https://github.com/redlabelvacations/tbi-base-images (branch: helix-upgrades)
#
# ECR accounts (per environment), using named AWS CLI profiles:
#   dev  -> profile tbi-dev   account 594765360358  (ca-central-1)
#   prod -> profile tbi-prod  account 489176460030  (ca-central-1)
#
# Prerequisites:
#   - Docker running locally
#   - AWS SSO/credentials active for the chosen profile(s):
#       aws sso login --profile tbi-dev
#       aws sso login --profile tbi-prod
#
# Usage:
#   # publish to both dev and prod ECR (default):
#   bash scripts/build-helix-base-images.sh
#
#   # only one environment:
#   TARGET=dev  bash scripts/build-helix-base-images.sh
#   TARGET=prod bash scripts/build-helix-base-images.sh
#
#   # build only, no push (local verification, no AWS needed):
#   PUSH=false bash scripts/build-helix-base-images.sh
#
# Overridable:
#   AWS_REGION (default ca-central-1)
#   DEV_PROFILE / DEV_ACCOUNT_ID    (default tbi-dev  / 594765360358)
#   PROD_PROFILE / PROD_ACCOUNT_ID  (default tbi-prod / 489176460030)
# =============================================================================

AWS_REGION="${AWS_REGION:-ca-central-1}"
PUSH="${PUSH:-true}"
TARGET="${TARGET:-all}"   # dev | prod | all
BASE_IMAGES_BRANCH="${BASE_IMAGES_BRANCH:-helix-upgrades}"
BASE_IMAGES_REPO="${BASE_IMAGES_REPO:-https://github.com/redlabelvacations/tbi-base-images.git}"

DEV_PROFILE="${DEV_PROFILE:-tbi-dev}"
DEV_ACCOUNT_ID="${DEV_ACCOUNT_ID:-594765360358}"
PROD_PROFILE="${PROD_PROFILE:-tbi-prod}"
PROD_ACCOUNT_ID="${PROD_ACCOUNT_ID:-489176460030}"

# Base images that are NEW / required by the Helix upgrade. tbi-php-73 is
# intentionally excluded (already published); add it here if a rebuild is needed.
IMAGES=(
  "tbi-php-85"
  "tbi-php-81"
)

WORKDIR="$(mktemp -d)"
trap 'rm -rf "${WORKDIR}"' EXIT

# Resolve which environments to process.
case "${TARGET}" in
  dev)  ENVS=("dev") ;;
  prod) ENVS=("prod") ;;
  all)  ENVS=("dev" "prod") ;;
  *) echo "ERROR: TARGET must be dev|prod|all (got '${TARGET}')"; exit 1 ;;
esac

profile_for() { [ "$1" = "prod" ] && echo "${PROD_PROFILE}" || echo "${DEV_PROFILE}"; }
account_for() { [ "$1" = "prod" ] && echo "${PROD_ACCOUNT_ID}" || echo "${DEV_ACCOUNT_ID}"; }

echo "=== Helix base image build ==="
echo "Targets : ${ENVS[*]}"
echo "Images  : ${IMAGES[*]}"
echo "Region  : ${AWS_REGION}"
echo "Push    : ${PUSH}"
echo

if ! docker info >/dev/null 2>&1; then
  echo "ERROR: Docker is not running."; exit 1
fi

echo "Cloning tbi-base-images (${BASE_IMAGES_BRANCH})..."
git clone --depth 1 --branch "${BASE_IMAGES_BRANCH}" "${BASE_IMAGES_REPO}" "${WORKDIR}/tbi-base-images"

# Build each base image once locally (same source for every target).
for img in "${IMAGES[@]}"; do
  ctx="${WORKDIR}/tbi-base-images/${img}"
  echo
  echo "----- build ${img} -----"
  [ -f "${ctx}/Dockerfile" ] || { echo "ERROR: ${ctx}/Dockerfile not found"; exit 1; }
  docker build -t "${img}:latest" "${ctx}"
done

if [ "${PUSH}" != "true" ]; then
  echo
  echo "=== Build-only mode: ${#IMAGES[@]} image(s) built, push skipped. ==="
  exit 0
fi

# Push to each target environment's ECR using its profile.
for env in "${ENVS[@]}"; do
  profile="$(profile_for "$env")"
  account="$(account_for "$env")"
  registry="${account}.dkr.ecr.${AWS_REGION}.amazonaws.com"

  echo
  echo "===== Publishing to ${env} ECR (profile=${profile}, account=${account}) ====="
  aws sts get-caller-identity --profile "${profile}" >/dev/null 2>&1 || {
    echo "ERROR: no valid credentials for profile '${profile}'. Run: aws sso login --profile ${profile}"; exit 1; }

  aws ecr get-login-password --region "${AWS_REGION}" --profile "${profile}" \
    | docker login --username AWS --password-stdin "${registry}"

  for img in "${IMAGES[@]}"; do
    aws ecr describe-repositories --repository-names "${img}" --region "${AWS_REGION}" --profile "${profile}" >/dev/null 2>&1 || \
      aws ecr create-repository --repository-name "${img}" \
        --image-tag-mutability MUTABLE --region "${AWS_REGION}" --profile "${profile}" >/dev/null
    docker tag "${img}:latest" "${registry}/${img}:latest"
    docker push "${registry}/${img}:latest"
    echo "Pushed ${registry}/${img}:latest"
  done
done

echo
echo "=== Done. Published ${#IMAGES[@]} base image(s) to: ${ENVS[*]}. ==="
