#!/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
task_family  = TASK_FAMILY  || TEAMCITY_PROJECT_NAME

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

  log "Updating `#{service_name}` in `#{nickname}` to use revision `#{task_revision}`"

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

  results = ecs.update_service cluster: cluster_name,
                               service: service_name,
                               task_definition: "#{task_family}:#{task_revision}",
                               desired_count: DESIRED_COUNT

  log "Update complete in #{nickname}. API Output:"
  log JSON.pretty_unparse(results.to_hash)
end
