#!/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 set_param(key, value)
  puts "##teamcity[setParameter name='#{key}' value='#{value}']"
end

aws_region = '$AWS_REGION'
aws_region_code = '$AWS_REGION_CODE'
deploy_role = '%deploy.role%'

info 'Updating task definition for %ecs.task.family%'
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

definition = JSON.parse('$TASK_DEFINITION', symbolize_names: true)
debug JSON.pretty_unparse(definition)

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.task.family%'
  )
end

ecs_client = Aws::ECS::Client.new region: aws_region, credentials: credentials
task = ecs_client.register_task_definition(definition)
debug JSON.pretty_unparse(task.to_h)

info 'Update to task definition complete!'

revisions = JSON.parse('%task.revisions%')
revisions[aws_region_code] = task.task_definition.revision
set_param('task.revisions', revisions.to_json)
