#!/bin/bash
set -e

case ${ENVIRONMENT} in
  "staging")
    export DEPLOY_ROLE_ARN="arn:aws:iam::219087926005:role/admin-panel-deploy-staging"
    ;;
  "production")
    export DEPLOY_ROLE_ARN="arn:aws:iam::196915980276:role/admin-panel-deploy-production"
    ;;
  "canary")
    export DEPLOY_ROLE_ARN="arn:aws:iam::196915980276:role/admin-panel-deploy-canary"
    ;;
  *)
    echo "Invalid Enviroment: ${ENVIRONMENT}"
    exit 1
    ;;
esac

export ECS_CLUSTER_NAME="admin-panel-${ENVIRONMENT}"
export ECS_SERVICE_NAME="admin-panel-${ENVIRONMENT}"
export ECS_REGION="us-west-2"

CREDS=($(aws sts assume-role \
  --role-arn "${DEPLOY_ROLE_ARN}" \
  --role-session-name "admin-panel-deploy-${ENVIRONMENT}" \
  --query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' \
  --output "text" \
  --duration-seconds 900 \
  --region ${ECS_REGION}))

await_deploy() {
  ecs="AWS_ACCESS_KEY_ID=${CREDS[0]} AWS_SECRET_ACCESS_KEY=${CREDS[1]} AWS_SESSION_TOKEN=${CREDS[2]} aws ecs describe-services \
    --service ${ECS_SERVICE_NAME} \
    --cluster ${ECS_CLUSTER_NAME} \
    --region ${ECS_REGION} \
    --output json"
  # Get the service's desired running instance count
  primary_desired_count="$(eval "${ecs}" | jq '.services[].deployments[] | select(.status=="PRIMARY") | .desiredCount')"

  success=
  # loop until it's up, or we hit ten minutes
  for _ in {1..120}; do
    echo -e "\nService deployment of ${ECS_SERVICE_NAME}, pending\n"
    
    # primary is the deployment that should be running -- usually this is what was just deployed
    primary_running_count="$(eval "${ecs}" | jq '.services[].deployments[] | select(.status=="PRIMARY") | .runningCount')"
    # active is the deployment that is spinning down
    active_running_count="$(eval "${ecs}" | jq '.services[].deployments[] | select(.status=="ACTIVE") | .runningCount')"

    if [[ "${primary_running_count}" -eq "${primary_desired_count}" && -z "${active_running_count}" ]]
    then
      # primary running and primary desired are equal, active is zero -- we should be steady state and fully live
      echo -e "\nService deployment of ${ECS_SERVICE_NAME} appears to be successful,\n ${primary_running_count} running out of ${primary_desired_count} desired.\n"
      success="TRUE"
      break;
    else
      # either the primary counts don't match or active is still draining -- we're not steady state yet
      echo -e "\nRUNNING CONTAINER COUNT :: ${primary_running_count}, DESIRED CONTAINER COUNT :: ${primary_desired_count}\n"
      sleep 5
    fi
  done

  # -z inside [[ ]] is a null/empty check in bash
  if [[ -z "${success}" ]]
  then
    # deploy never made it to steady state :(
    echo -e "\nService deployment of ${ECS_SERVICE_NAME}, timed out after 600 seconds\n"
    return 1
  else
    # we live.
    return 0
  fi
}

await_deploy
