#!/usr/bin/env bash
# Authenticate to ECR and pull Helix container images
set -euo pipefail

REGION="${AWS_REGION:-ap-southeast-1}"
IMAGE_TAG="${1:-latest}"

# Get ECR registry URL from account
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
ECR_REGISTRY="${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com"

echo "Authenticating to ECR (${ECR_REGISTRY})..."
aws ecr get-login-password --region "$REGION" | \
  docker login --username AWS --password-stdin "$ECR_REGISTRY"

# Reclaim only *dangling* layers here (cheap, safe). The aggressive
# ``docker image prune -af`` that frees old sha-tagged releases moved to
# the post-deploy success path in deploy.sh: ``-af`` deletes every image
# not attached to a RUNNING container, which — run before ``compose up``
# — deleted both the layers the image-release ``prepull`` job had just
# warmed AND the image we're about to pull, forcing a cold pull on every
# single deploy. Pruning after the new containers are up lets Docker's
# "in use" guard protect the just-deployed image while still reclaiming
# the previous release.
echo "Pruning dangling layers to free disk space..."
docker image prune -f --filter "dangling=true" || true

echo "Pulling images (tag: ${IMAGE_TAG})..."
# Parallel pulls — three repos × ~10-20 s each becomes max(~10-20 s)
# instead of sum. The Docker daemon serializes layer downloads
# internally so this only fans out the manifest+blob fetches, but that
# is exactly the network-bound slice that benefits.
#
# In the common case the image-release ``prepull`` SSM job already
# warmed the layer cache before we got here, so each pull is a cheap
# ``Image is up to date`` no-op. The parallel form below stays correct
# whether the cache is warm or cold.
PULL_PIDS=()
PULL_LOG_DIR="$(mktemp -d)"
trap 'rm -rf "$PULL_LOG_DIR"' EXIT

for repo in helix-server helix-web helix-worker; do
  IMAGE="${ECR_REGISTRY}/${repo}:${IMAGE_TAG}"
  echo "  Pulling ${IMAGE}..."
  ( docker pull "${IMAGE}" >"${PULL_LOG_DIR}/${repo}.log" 2>&1 ) &
  PULL_PIDS+=("$!:${repo}")
done

PULL_FAILED=0
for entry in "${PULL_PIDS[@]}"; do
  pid="${entry%%:*}"
  repo="${entry#*:}"
  if ! wait "$pid"; then
    echo "  FAILED: ${repo}" >&2
    cat "${PULL_LOG_DIR}/${repo}.log" >&2
    PULL_FAILED=1
  fi
done

if [[ "$PULL_FAILED" -ne 0 ]]; then
  echo "One or more image pulls failed; aborting deploy." >&2
  exit 1
fi

# Update compose .env with current registry and tag
cat > /opt/helix/compose/.env <<EOF
ECR_REGISTRY=${ECR_REGISTRY}
IMAGE_TAG=${IMAGE_TAG}
AWS_REGION=${REGION}
EOF

echo "Images pulled and .env updated."
