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

require 'aws-sdk'
require 'json'

require_relative './patches'
require_relative './constants'
require_relative './helpers'

cluster_name = CLUSTER_NAME || TEAMCITY_PROJECT_NAME
service_name = SERVICE_NAME || TEAMCITY_PROJECT_NAME

started_at = Time.now
success = {}

DEPLOY_ENV.each do |nickname|
  aws_region = AWS_REGIONS[nickname]
  task_revision = ENV["TASK_REVISION_#{nickname.upcase}"]

  log "#{nickname.upcase}: Verifying deploy of revision `#{task_revision}` to `#{service_name}`"

  ecs = authenticate account: DEPLOY_AWS_ACCOUNT, region: aws_region, assume_role: DEPLOY_ASSUME_ROLE,
                     session_name: "verifying-#{service_name}-to-#{IMAGE_VERSION}"

  success[nickname] = false
  until success[nickname]
    res = ecs.describe_services cluster: cluster_name, services: [service_name]

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

    if is_primary
      if deploy.size > 1
        # deploy still pending, wait till it finishes (max 10 mins)
        break if Time.now > started_at + 600
        sleep 10
        next
      else
        # last deploy standing, we win
        success[nickname] = true
        log "#{nickname.upcase}: Deploy complete for `#{service_name}`, revision `#{task_revision}`"
      end
    elsif primary_revision.to_i > task_revision.to_i
      # a more recent deploy has taken our place, exit gracefully
      success[nickname] = true
      log "#{nickname.upcase}: A more recent deploy may exist for `#{service_name}` (target: `#{task_revision}`, primary: `#{primary_revision}`)"
    else
      # someone did something manually, maybe? well, crap.
      break
    end
  end

  log "#{nickname.upcase}: Deploy failed for `#{service_name}`, revision `#{task_revision}`" unless success[nickname]
end

abort 'Verification failed' if success.value?(false)
