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

require 'aws-sdk'
require 'json'

require_relative './patches'
require_relative './constants'
require_relative './helpers'

task_family = TASK_FAMILY

log "Updating the task definition `#{task_family}` to use #{IMAGE_VERSION}"

aws_region = 'us-west-2'
nickname = 'pdx'

ecs = authenticate account: DEPLOY_AWS_ACCOUNT, region: aws_region, assume_role: DEPLOY_ASSUME_ROLE,
                    session_name: "updating-#{task_family}-to-#{IMAGE_VERSION}"

results = ecs.register_task_definition \
family: task_family,
task_role_arn: "arn:aws:iam::#{DEPLOY_AWS_ACCOUNT}:role/#{regionalized_role(TASK_ROLE, aws_region)}",
container_definitions: [
  {
    name: task_family,
    essential: true,
    image: "#{AWS_ECR_URL}/aws-es-proxy:#{IMAGE_VERSION}",
    memory: 512,
    environment: [
        { name: 'UPSTREAM_URL', value: UPSTREAM_URL },
        { name: 'UPSTREAM_SERVICE_NAME', value: UPSTREAM_SERVICE_NAME },
        { name: 'UPSTREAM_REGION', value: UPSTREAM_REGION },
        { name: 'LISTEN_PORT', value: LISTEN_PORT }
    ],
    port_mappings: [
        { host_port: 0, container_port: 9200, protocol: 'tcp' },
    ],
    log_configuration: {
        log_driver: 'awslogs',
        options: {
        'awslogs-group' => task_family,
        'awslogs-region' => 'us-west-2',
        'awslogs-stream-prefix' => "#{task_family}-#{nickname}"
        }
    },
    ulimits: [
        {
            name: 'nofile',
            soft_limit: 131072,
            hard_limit: 131072
        }
    ]
  }
]

log "Update complete in #{nickname}. API Output:"
log JSON.pretty_unparse(results.to_hash)

task_revision = results.task_definition.revision

log "Updating env.TASK_REVISION_#{nickname.upcase} to `#{task_revision}`"
set_param "env.TASK_REVISION_#{nickname.upcase}", task_revision