#!/usr/bin/env bash
set -e

# Note: Do not run this script directly, use `make`. Or better yet, let Jenkins do it.
#
# Setup:
# 1. Install AWS CLI (http://docs.aws.amazon.com/cli/latest/userguide/tutorial-ec2-ubuntu.html#install-cli)
# 2. Install jq using `brew install jq`
# 3. Ensure you have active AWS credentials in environment vars for `twitch-mdaas-ingest-dev` or `twitch-mdaas-ingest-prod`.

INPUT_IMAGE="$1"
TAG="$2"
IF_CANARY="$3"

if [[ -z "$TAG" ]]; then
  TAG="latest"
fi

if [ -z "$INPUT_IMAGE" ]; then
  echo "Usage: $0 <image> [tag]"
  exit 1
fi

cd "$(dirname $0)"

# Determine which ECS cluster, service, and ECR repository to use for deploying.
DEPLOY_TARGET="Ingest"
CLUSTER_ARN=$(aws resourcegroupstaggingapi get-resources --tag-filters Key=DeployCluster,Values=$DEPLOY_TARGET | jq -r ".ResourceTagMappingList[0].ResourceARN")

## Determine service ARN depending on if this is a canary deployment
SERVICE_ARNs=$(aws ecs list-services --cluster $CLUSTER_ARN | jq -r ".serviceArns | .[]")
for ARN in ${SERVICE_ARNs[@]}
do
    if [[ ${ARN} == *"Canary"* ]]; then
      CANARY_ARN=${ARN}
    else
      SERVICE_ARN=${ARN}
    fi
done

if [[ ${IF_CANARY} = "canary" ]]; then
    SERVICE_ARN=${CANARY_ARN}
fi

REPOSITORY_ARN=$(aws resourcegroupstaggingapi get-resources --tag-filters Key=DeployRepo,Values=$DEPLOY_TARGET | jq -r ".ResourceTagMappingList[0].ResourceARN")
CLUSTER=$(aws ecs describe-clusters --cluster $CLUSTER_ARN | jq -r ".clusters[0].clusterName")
SERVICE=$(aws ecs describe-services --cluster $CLUSTER_ARN --service $SERVICE_ARN | jq -r ".services[0].serviceName")
REPOSITORY=$(aws ecr describe-repositories | jq -r ".repositories[] | select ( .repositoryArn == \"$REPOSITORY_ARN\" ) | .repositoryUri")

# Log into ECR
`aws ecr get-login --no-include-email`

# Deploy tagged version
DEPLOY_IMAGE_TAGGED="${REPOSITORY}:${TAG}"
docker tag "$INPUT_IMAGE" "$DEPLOY_IMAGE_TAGGED"
docker push "$DEPLOY_IMAGE_TAGGED"
vendor/ecs-deploy --cluster "$CLUSTER" --service-name "$SERVICE" --image "$DEPLOY_IMAGE_TAGGED" --timeout 600

# After successful non-canary deploy, update the latest tag
if [[ ${IF_CANARY} != "canary" ]]; then
    DEPLOY_IMAGE_LATEST="${REPOSITORY}:latest"
    docker tag "$INPUT_IMAGE" "$DEPLOY_IMAGE_LATEST"
    docker push "$DEPLOY_IMAGE_LATEST"
fi
