#!/usr/bin/env ruby
# frozen_string_literal: true

require 'aws-sdk'
require 'json'

def info(message)
  puts "##teamcity[message text='#{message}' SEVERITY='INFO']"
end

def debug(message)
  puts "##teamcity[message text='#{message}' SEVERITY='DEBUG']"
end

def fatal(message)
  puts "##teamcity[buildProblem description='#{message}']"
end

aws_region = '$AWS_REGION'
aws_region_code = '$AWS_REGION_CODE'
deploy_role = '%deploy.role%'

info 'Verifying ECS Service: %ecs.service%'
info "Target region: #{aws_region_code} (#{aws_region})"

unless '%deploy.regions%'.split(',').collect(&:strip).include?(aws_region_code)
  info "Skipping this step as #{aws_region_code} is not a targeted region."
  exit(0)
end

revisions = JSON.parse('%task.revisions%')
unless revisions.keys.include?(aws_region_code)
  fatal "No task revision for #{aws_region_code}"
  exit(1)
end

if deploy_role.empty?
  credentials = Aws::InstanceProfileCredentials.new
else
  credentials = Aws::AssumeRoleCredentials.new(
      client: Aws::STS::Client.new(region: aws_region),
      role_arn: "arn:aws:iam::%ecs.account%:role/#{deploy_role}",
      role_session_name: 'updating-%ecs.service%'
  )
end

ecs_client = Aws::ECS::Client.new region: aws_region, credentials: credentials
revision = revisions[aws_region_code].to_i
definition_revision = "%ecs.service%:#{revision}"

info "Target revision: #{definition_revision}"

while true
  sleep 10

  response = ecs_client.describe_services cluster: '%ecs.cluster%', services: ['%ecs.service%']
  deployments = response.services[0].deployments

  primary_deployment = deployments.select {|deployment| deployment.status == 'PRIMARY'}[0]
  primary_revision = primary_deployment.task_definition.split(':')[-1].to_i

  if primary_revision > revision
    info "A more recent revision is currently the primary deployment."
    break
  end

  if primary_revision < revision
    fatal "Somehow a older revision is currently the primary deployment."
    exit(1)
  end

  break if primary_revision == revision && deployments.count == 1
  debug "Deploy is still pending..."
end

info "Deployment verification complete!"
