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

require 'aws-sdk'
require 'json'

DEPLOY_SERVICE = '%deploy.service%'
IMAGE = "994136867826.dkr.ecr.us-west-2.amazonaws.com/%ecr.repo%:%build.number%"

def task_definition(region)
  {
      family: DEPLOY_SERVICE,
      task_role_arn: task_role_arn(region: region),
      container_definitions: [
          {
              name: DEPLOY_SERVICE,
              essential: true,
              image: IMAGE,
              memory: 1024,
              environment: task_environment(region: region),
              port_mappings: [
                  { container_port: 8080, protocol: 'tcp' }
              ],
              log_configuration: {
                  log_driver: 'awslogs',
                  options: {
                      'awslogs-group' => DEPLOY_SERVICE,
                      'awslogs-region' => 'us-west-2',
                      'awslogs-stream-prefix' => region
                  }
              }
          }
      ]
  }
end

task_revisions = {}

deploy_environments.each do |environment|
  if task_revisions.include?(environment)
    fatal "Duplicate deploy environment `#{environment}`.  Please cleanup settings and try again."
    return
  end

  info "Updating the task definition #{DEPLOY_SERVICE} to version #{IMAGE} in #{environment}"

  definition = task_definition(environment)
  debug JSON.pretty_unparse(definition)

  task = ecs_client(region: environment).register_task_definition(definition)
  info "Updating complete in #{environment}."
  debug JSON.pretty_unparse(task.to_h)

  task_revisions[environment] = task.task_definition.revision
end

set_param("task.revisions", task_revisions.to_json)
