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

require 'aws-sdk'
require 'json'

require_relative './helpers'

def task_definition(region)
  {
    family: task_family,
    task_role_arn: task_role_arn(region: region),
    container_definitions: [
      {
        name: task_family,
        essential: true,
        image: image,
        memory: 1024,
        environment: task_environment(:arcana_bucket, :arcana_system_prefix, :service_id),
        port_mappings: [],
        log_configuration: {
          log_driver: 'awslogs',
          options: {
            'awslogs-group' => task_family,
            'awslogs-region' => mapped_region(env(:deploy_cloudwatch_env)),
            'awslogs-stream-prefix' => "#{task_family}-#{region}"
          }
        }
      }
    ]
  }
end

deploy_env.each do |env|
  log "Updating the task definition #{task_family} to version #{image_version} in #{env}."
  result = ecs_client(region: env).register_task_definition task_definition(env)

  puts JSON.pretty_unparse(task_definition(env))

  log "Updating complete in #{env}. API Output:"
  log JSON.pretty_unparse result.to_hash

  task_revision = result.task_definition.revision
  log "Updating env.TASK_REVISION_#{env.upcase} to `#{task_revision}`"
  set_param "env.TASK_REVISION_#{env.upcase}", task_revision
end
