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

require 'aws-sdk'
require 'json'
require 'yaml'

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

PROJECTS = YAML.load_file(File.expand_path("../../config/projects/#{RACK_ENV}.yml", __FILE__))

task_family_base = (TASK_FAMILY || TEAMCITY_PROJECT_NAME) + '-worker'

nickname = :pdx
aws_region = AWS_REGIONS[nickname]

PROJECTS[:projects].each_key do |project|
  task_family = "#{task_family_base}-#{project.to_s.downcase.tr('/', '-')}"

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

  ecs = authenticate account: DEPLOY_AWS_ACCOUNT, region: aws_region, assume_role: DEPLOY_ASSUME_ROLE,
                     session_name: "updating-#{task_family}-to-#{IMAGE_VERSION}"[0..63].tr('/', '-')

  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,
        command: ['worker'],
        image: "#{AWS_ECR_URL}/#{TEAMCITY_PROJECT_NAME}:#{IMAGE_VERSION}",
        memory: 256,
        environment: [
          { name: 'RACK_ENV', value: RACK_ENV },
          { name: 'ARCANA_BUCKET', value: ARCANA_BUCKET },
          { name: 'ARCANA_KEY', value: ARCANA_KEY },
          { name: 'ARCANA_REGION', value: ARCANA_REGION },
          { name: 'ARCANA_SERVICE_ID', value: ARCANA_SERVICE_ID },
          { name: 'AUDIT_S3_BUCKET', value: AUDIT_S3_BUCKET },
          { name: 'AUDIT_SNS_TOPIC', value: AUDIT_SNS_TOPIC },
          { name: 'AWS_REGION', value: aws_region },
          { name: 'GITHUB_URL', value: GITHUB_URL },
          { name: 'POLL_INTERVAL', value: POLL_INTERVAL },
          { name: 'PROJECT', value: project },
          { name: 'REDIS_URL', value: REDIS_URL },
          { name: 'SESSION_KEY', value: SESSION_KEY },
          { name: 'SITE_URL', value: SITE_URL},
          { name: 'TEAMCITY_URL', value: TEAMCITY_URL}
        ],
        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_#{task_family.tr('-', '_').upcase}_#{nickname.upcase} to `#{task_revision}`"
  set_param "env.TASK_REVISION_#{task_family.tr('-', '_').upcase}_#{nickname.upcase}", task_revision
end
