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

require 'aws-sdk'
require 'json'

require_relative './helpers'

def rule
  {
    name: task_family,
    schedule_expression: 'rate(1 minute)',
    state: 'ENABLED',
    description: env(:task_description)
  }
end

def target(env, task_revision)
  {
    rule: task_family,
    targets: [
      {
        id: task_family,
        arn: ecs_cluster_arn(region: env),
        role_arn: executor_role_arn(region: env),
        input: '{}',
        ecs_parameters: {
          task_definition_arn: task_definition_arn(region: env, version: task_revision),
          task_count: env(:task_count) || 1
        }
      }
    ]
  }
end

deploy_env.each do |env|
  task_revision = env(:"task_revision_#{env.downcase}")

  if task_revision.nil?
    log "Unable to identify the task revision for #{env}."
    next
  end

  log "Updating the CloudWatch rule #{task_family} in #{env} to target #{task_revision}."

  result = events_client(region: env).put_rule rule
  log "Updating rule complete in #{env}. API Output:"
  log JSON.pretty_unparse result.to_h

  result = events_client(region: env).put_targets target(env, task_revision)
  log "Updating rule target complete in #{env}. API Output:"
  log JSON.pretty_unparse result.to_h
end

