#!/usr/bin/env ruby
# frozen_string_literal: true

## Logging

def debug(message)
  puts "##teamcity[message text='#{message}' SEVERITY='DEBUG']"
end

def fatal(message)
  puts "##teamcity[buildProblem description='#{message}']"
end

def info(message)
  puts "##teamcity[message text='#{message}' SEVERITY='INFO']"
end

def warn(message)
  puts "##teamcity[message text='#{message}' SEVERITY='WARNING']"
end

def set_param(key, value)
  puts "##teamcity[setParameter name='#{key}' value='#{value}']"
end

## Helpers

def credentials(region:, account: '%deploy.account%', assume_role: '%deploy.role%', session_name: "updating-%deploy.service%-to-%build.number%")
  region = mapped_region(region)

  if assume_role.empty?
    Aws::InstanceProfileCredentials.new
  else
    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 deploy_environments
  @deploy_environments ||= "%deploy.environments%".split(',').collect(&:strip)
end

def ecs_client(region:)
  region = mapped_region(region)
  Aws::ECS::Client.new region: region, credentials: credentials(region: region)
end

def env(key)
  @env ||= ENV.collect {|name, value| [name.downcase.to_sym, value]}.to_h
  @env[key]
end

def mapped_region(region)
  standard_region_mapping[region.to_sym] || region
end

def pretty_region(region:)
  parts = region.to_s.split('-')
  "#{parts[0].upcase}#{parts[1].capitalize}#{parts[2]}"
end

def regionalized_role(region:, role:)
  return role unless role =~ /^.*-(.*)-.*$/

  region = mapped_region(region)
  parts = role.split('-')
  "#{parts[0]}-#{pretty_region(region: region)}-#{parts[2]}"[0..62]
end

def standard_region_mapping
  @standard_region_mapping ||= {
      bom: 'ap-south-1',
      cdg: 'eu-west-3',
      cle: 'us-east-2',
      dub: 'eu-west-1',
      fra: 'eu-central-1',
      gru: 'sa-east-1',
      iad: 'us-east-1',
      icn: 'ap-northeast-2',
      lhr: 'eu-west-2',
      nrt: 'ap-northeast-1',
      pdx: 'us-west-2',
      sin: 'ap-southeast-1',
      sjc: 'us-west-1',
      syd: 'ap-southeast-2',
      yul: 'ca-central-1'
  }
end

def task_environment(region:)
  [
      { name: 'AWS_REGION', value: mapped_region(region) },
  ]

  # keys.collect {|key| {name: key.to_s.upcase, value: env(key)}}
end

def task_role_arn(region:)
  "arn:aws:iam::%deploy.account%:role/#{regionalized_role(region: region, role: '%task.role%')}"
end
