#!/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__))

cluster_name = CLUSTER_NAME || TEAMCITY_PROJECT_NAME
service_name_base = (SERVICE_NAME || TEAMCITY_PROJECT_NAME) + '-worker'
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('/', '-')}"
  service_name = "#{service_name_base}-#{project.to_s.downcase.tr('/', '-')}"

  task_revision = ENV["TASK_REVISION_#{task_family.tr('-', '_').upcase}_#{nickname.upcase}"]

  log "Updating `#{service_name}` in `#{nickname}` to use revision `#{task_revision}`"

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

  results = ecs.update_service cluster: cluster_name,
                               service: service_name,
                               task_definition: "#{task_family}:#{task_revision}",
                               desired_count: 1

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