#!/usr/bin/env ruby
require 'aws-sdk'
require 'json'

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

service_name = TEAMCITY_PROJECT_NAME
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}`"

  if DEPLOY_ASSUME_ROLE.nil?
    ecs = Aws::ECS::Client.new region: aws_region, credentials: Aws::InstanceProfileCredentials.new()
  else
    ecs = Aws::ECS::Client.new region: aws_region, credentials: Aws::AssumeRoleCredentials.new(
        client: Aws::STS::Client.new(region: aws_region),
        role_arn: "arn:aws:iam::#{DEPLOY_AWS_ACCOUNT}:role/#{regionalized_role(DEPLOY_ASSUME_ROLE, aws_region)}",
        role_session_name: "updating-#{service_name}-to-#{IMAGE_VERSION}"
    )
  end

  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