#!/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 scheduled task: %ecs.task%'
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.task%'
  )
end

rule_definition = {
    name: '%ecs.task%',
    schedule_expression: '%ecs.task.schedule%',
    description: 'Scheduling rule for task %ecs.task%',
    state: 'ENABLED'
}

targets_definition = {
    rule: '%ecs.task%',
    targets: [
        {
            id: '%ecs.task%',
            arn: "arn:aws:ecs:#{aws_region}:%ecs.account%:cluster/%ecs.cluster%",
            role_arn: 'arn:aws:iam::%ecs.account%:role/$TASK_EXECUTOR_ROLE',
            input: '{}',
            ecs_parameters: {
                launch_type: '%ecs.launch.type%',
                task_definition_arn: "arn:aws:ecs:#{aws_region}:%ecs.account%:task-definition/%ecs.task.family%:#{revisions[aws_region_code]}",
                task_count: $DESIRED_COUNT
            }
        }
    ]
}

if '%ecs.launch.type%' == 'FARGATE'
  network_configuration = JSON.parse('$ECS_NETWORK_CONFIGURATION', symbolize_names: true)
  targets_definition[:targets].each {|target| target[:ecs_parameters][:network_configuration] = network_configuration}
end

events_client = Aws::CloudWatchEvents::Client.new region: aws_region, credentials: credentials

rule = events_client.put_rule rule_definition
debug JSON.pretty_unparse(rule.to_h)

targets = events_client.put_targets targets_definition
debug JSON.pretty_unparse(targets.to_h)

info 'Update to the scheduled task complete!'
