#!/bin/bash

set -e -o pipefail

run_ecr_command() {
  aws ecr "$@" --registry-id "$ECR_ACCOUNT_ID" --repository-name "$IMAGE_NAME" --output text
}

DIGEST=$(run_ecr_command describe-images --image-ids imageTag="$IMAGE_TAG" --query 'imageDetails[0].imageDigest')

echo "Image digest for $IMAGE_NAME:$IMAGE_TAG is $DIGEST"

for TAG in $(run_ecr_command describe-images --image-ids imageDigest="$DIGEST" --query 'imageDetails[0].imageTags[]'); do
  if [ "$TAG" == "$NEW_TAG" ]; then
    echo "Image with tag $NEW_TAG already exists and matches the digest $DIGEST"
    exit 0
  fi
done

MANIFEST=$(run_ecr_command batch-get-image --image-ids imageDigest="$DIGEST" --query 'images[0].imageManifest')

echo "Retagging image $IMAGE_NAME:$IMAGE_TAG to $NEW_TAG"
run_ecr_command put-image --image-tag "$NEW_TAG" --image-manifest "$MANIFEST" --query 'image.imageId.imageDigest'
