#!/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}"

nickname = :pdx
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}"[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: ['server'],
      image: "#{AWS_ECR_URL}/#{TEAMCITY_PROJECT_NAME}:#{IMAGE_VERSION}",
      memory: 512,
      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: 'BOUNCER_AUD', value: BOUNCER_AUD },
        { name: 'BOUNCER_ISS', value: BOUNCER_ISS },
        { name: 'BOUNCER_PUBLIC_KEY_MODULUS', value: BOUNCER_PUBLIC_KEY_MODULUS },
        { name: 'BOUNCER_PUBLIC_KEY_EXPONENT', value: BOUNCER_PUBLIC_KEY_EXPONENT },
        { name: 'GITHUB_URL', value: GITHUB_URL },
        { 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_#{nickname.upcase} to `#{task_revision}`"
set_param "env.TASK_REVISION_#{nickname.upcase}", task_revision
