#!/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 || TEAMCITY_PROJECT_NAME

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

DEPLOY_ENV.each do |nickname|
  aws_region = AWS_REGIONS[nickname]

  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}/#{TEAMCITY_PROJECT_NAME}:#{IMAGE_VERSION}",
        memory: 3072,
        environment: [
          {name: 'VARNISH_CACHE_SIZE', value: VARNISH_CACHE_SIZE},
          {name: 'VARNISH_BIGFILES_CACHE_SIZE', value: VARNISH_BIGFILES_CACHE_SIZE},
          {name: 'VARNISH_TTL', value: VARNISH_TTL},
          {name: 'VICARIUS_ORIGIN_ENV', value: (VICARIUS_STAGE == 'tools' ? nickname : ORIGIN_ENVS[VICARIUS_STAGE.to_sym][nickname])},
          {name: 'VICARIUS_STAGE', value: VICARIUS_STAGE},
          {name: 'VICARIUS_REGION', value: nickname}
        ],
        port_mappings: [
          {host_port: 0, container_port: 8080, protocol: 'tcp'}
        ],
        log_configuration: {
          log_driver: 'awslogs',
          options: {
            'awslogs-group' => task_family,
            'awslogs-region' => DEPLOY_CLOUDWATCH_REGION,
            'awslogs-stream-prefix' => "#{task_family}-#{nickname}"
          }
        }
      }
    ]

  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
end
