# frozen_string_literal: true

def log(message)
    puts "##teamcity[message text='#{message}']"
  end
  
  def set_param(key, value)
    puts "##teamcity[setParameter name='#{key}' value='#{value}']"
  end
  
  def status exit_code, message
    log message
    puts "##teamcity[buildStatus status='#{exit_code == 0 ? 'Success' : 'Failed'}' text='#{message}']"
    exit exit_code
  end
  
  def authenticate(account:, region:, assume_role: nil, session_name:)
    if assume_role.empty?
      Aws::ECS::Client.new region: region, credentials: Aws::InstanceProfileCredentials.new
    else
      Aws::ECS::Client.new region: region, credentials: Aws::AssumeRoleCredentials.new(
        client: Aws::STS::Client.new(region: region),
        role_arn: "arn:aws:iam::#{account}:role/#{assume_role}",
        role_session_name: session_name
      )
    end
  end

  def pretty_region(region)
    parts = region.to_s.split('-')
    "#{parts[0].upcase}#{parts[1].capitalize}#{parts[2]}"
  end
  
  def regionalized_role(base, region)
    return base unless base =~ /^.*-(.*)-.*$/
    parts = base.split('-')
    "#{parts[0]}-#{pretty_region(region)}-#{parts[2]}"[0..62]
  end