# frozen_string_literal: true

require 'litany/resource'
require 'litany/mixins'

module Litany
  class ECSScheduledTask < MetaResource
    include ServiceRoot

    child_resource CloudWatchLogGroup, :log_group

    flag :fargate, false

    property :task_family, nil, [nil, String]

    resource_collection IAMRole, :role
    resource_collection KMSKey, :kms_key, required: false

    def ecs
      parent_resource.is_a?(ECS) ? parent_resource : parent_resource.cluster
    end

    # The events permissions needed to execute the task on the schedule
    def executor_role(&block)
      role(:"#{name}_executor", &block)
    end

    # Permissions for the task itself
    def task_role(&block)
      role(:"#{name}_task", &block)
    end

    # Used by fargate tasks
    def task_execution_role(&block)
      role(:"#{name}_task_execution", &block)
    end

    def finalize_resource
      task_definition_arn = arn_builder(service: 'ecs', resource: 'task-definition', path: "#{task_family || name}:*")

      executor_role.trust(service: 'events.amazonaws.com')
      executor_role.allow actions: 'ecs:RunTask', resource: task_definition_arn, condition: { ArnEquals: { 'ecs:cluster': ref(ecs.cluster, :Arn) } }

      task_role.trust(service: 'ecs-tasks.amazonaws.com')

      if ArcanaSupport.automatic?
        key = kms_key(service_id)
        key.allow role: :task_role
        key.allow role: ArcanaSupport.instance.admin_role

        task_role.allow actions: 's3:GetObject', resource: join([ref(ArcanaSupport.instance.bucket, :Arn), service_id, '*'], '/')
      end

      return unless fargate?

      executor_role.allow actions: 'iam:PassRole', resource: ref(task_execution_role, :Arn), condition: { StringLike: { 'iam:PassedToService': 'ecs-tasks.amazonaws.com' } }
      executor_role.allow actions: 'iam:PassRole', resource: ref(task_role, :Arn), condition: { StringLike: { 'iam:PassedToService': 'ecs-tasks.amazonaws.com' } }

      task_execution_role.trust service: 'ecs-tasks.amazonaws.com'
      task_execution_role.managed_policy 'arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy'
    end
  end
end
