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

require 'aws-sdk'
require 'json'


deploy_service = '%deploy.service%'
task_revisions = JSON.parse('%task.revisions%')

uncovered_envs = deploy_environments - task_revisions.keys
if uncovered_envs.count.positive?
  fatal "Found #{uncovered_envs.count} environment(s) without task_revisions. Uncovered: #{uncovered_envs.inspect}"
  return
end

verified = {}

while true
  sleep 10

  deploy_environments.each do |environment|
    next if verified.include?(environment)

    revision = task_revisions[environment].to_i
    definition = "#{deploy_service}:#{task_revisions[environment]}"

    info "#{environment}: Verifying deploy of `#{deploy_service}` to `#{definition}`."

    response = ecs_client(region: environment).describe_services cluster: '%deploy.cluster%', services: [deploy_service]

    deploys = response.services[0].deployments
    primary_deploy = deploys.select {|d| d.status == 'PRIMARY'}[0]
    primary_revision = primary_deploy.task_definition.split(':')[-1].to_i

    if primary_revision > revision
      warn "#{environment}: A more recent revision is currently the primary deployment. Target: #{revision}; Primary: #{primary_revision}."
      verified[environment] = true
      next
    end

    if primary_revision < revision
      fatal "#{environment}: Somehow the primary revision is older than what we're trying to deploy. Target: #{revision}; Primary: #{primary_revision}."
      verified[environment] = false
      next
    end

    if deploys.count == 1
      info "#{environment}: Deploy complete. Target: #{revision}; Primary: #{primary_revision}."
      verified[environment] = true
    end

    debug "#{environment}: Deploy is still pending... Target: #{revision}; Primary: #{primary_revision}."
  end

  break if verified.count == deploy_environments.count
end

succeeded = verified.values.count(true)
failed = verified.values.count(false)
info "All deploy regions have been verified. Succeeded: #{succeeded}; Failed: #{failed}."
