#!/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 'Updating 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

definition_revision = "%ecs.task.family%:#{revisions[aws_region_code]}"
service = ecs_client.update_service cluster: '%ecs.cluster%', service: '%ecs.service%', task_definition: definition_revision, desired_count: '$DESIRED_COUNT'
debug JSON.pretty_unparse(service.to_h)

info 'Update to the service complete!'
