#!/bin/bash

# This script retrieves the container image and task definition revision
# for a given cluster+service. If it can't retrieve it, assume
# this is the initial deployment and default to "latest".
defaultImageTag='latest'

export AWS_REGION=${AWS_REGION:-us-west-2}

# Exit if any of the intermediate steps fail
set -e

# Get parameters from stdin
eval "$(jq -r '@sh "service=\(.service) cluster=\(.cluster)"')"

taskDefinitionID="$(aws ecs describe-services --region "$AWS_REGION" --service $service --cluster $cluster | jq -r .services[0].taskDefinition)"

# If a task definition is already running in AWS, use the revision and image tag from it
if [[ ! -z "$taskDefinitionID" && "$taskDefinitionID" != "null" ]]; then {
  taskDefinitionRevision="$(echo "$taskDefinitionID" | sed 's/^.*://')"
  taskDefinition="$(aws ecs describe-task-definition --region "$AWS_REGION" --task-definition $taskDefinitionID)"
  containerImage="$(echo "$taskDefinition" | jq -r .taskDefinition.containerDefinitions[0].image)"
  imageTag="$(echo "$containerImage" | awk -F':' '{print $2}')"

# Default to "latest" if taskDefinition doesn't exist
# Set revision to 0 so terraform logic uses task definition from terraform
} else {
  imageTag=$defaultImageTag
  taskDefinitionRevision='0'
}
fi

# Generate a JSON object containing the image tag.
jq -n --arg imageTag $imageTag --arg taskDefinitionRevision $taskDefinitionRevision '{image_tag: $imageTag, task_definition_revision: $taskDefinitionRevision}'

exit 0