{% set config = merged_configs.get('aws_ecs_task_definition', {}) %}
{% set comments = compliance_comments.get('aws_ecs_task_definition', []) %}
# ------------------------------------------------------------------------------
# ECS Task Definition
# ------------------------------------------------------------------------------
{% for comment in comments %}
# {{ comment }}
{% endfor %}

resource "aws_ecs_task_definition" "this" {
  family                   = "{{ config.get('family', project_id ~ '-task') }}"
  requires_compatibilities = {{ config.get('requires_compatibilities', '["FARGATE"]') }}
  network_mode             = "{{ config.get('network_mode', 'awsvpc') }}"
  cpu                      = "{{ config.get('cpu', '256') }}"
  memory                   = "{{ config.get('memory', '512') }}"

  execution_role_arn = {{ config.get('execution_role_arn', 'aws_iam_role.ecs_exec.arn') }}
  task_role_arn      = {{ config.get('task_role_arn', 'null') }}

  container_definitions = jsonencode([
    {
      name      = "{{ config.get('container_name', 'app') }}"
      image     = "{{ config.get('container_image', 'public.ecr.aws/nginx/nginx:latest') }}"
      cpu       = {{ config.get('container_cpu', 256) }}
      memory    = {{ config.get('container_memory', 512) }}
      essential = true

      portMappings = [
        {
          containerPort = {{ config.get('container_port', 8080) }}
          protocol      = "tcp"
        }
      ]

      logConfiguration = {
        logDriver = "awslogs"
        options = {
          "awslogs-group"         = "{{ config.get('log_group', '/ecs/' ~ project_id) }}"
          "awslogs-region"        = var.region
          "awslogs-stream-prefix" = "{{ config.get('log_stream_prefix', 'ecs') }}"
        }
      }

      environment = []
      secrets     = []
    }
  ])

  runtime_platform {
    operating_system_family = "{{ config.get('os_family', 'LINUX') }}"
    cpu_architecture        = "{{ config.get('cpu_architecture', 'X86_64') }}"
  }

  tags = {
    Name      = "{{ config.get('family', project_id ~ '-task') }}"
    ManagedBy = "complyform"
  }
}

resource "aws_iam_role" "ecs_exec" {
  name = "{{ project_id }}-ecs-exec-role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRole"
        Effect = "Allow"
        Principal = {
          Service = "ecs-tasks.amazonaws.com"
        }
      }
    ]
  })

  tags = {
    Name      = "{{ project_id }}-ecs-exec-role"
    ManagedBy = "complyform"
  }
}

resource "aws_iam_role_policy_attachment" "ecs_exec" {
  role       = aws_iam_role.ecs_exec.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}
