locals {
  dd_env_vars = concat(
    var.dd_env_vars,
    [
      {
        "name": "DD_SITE",
        "value": "datadoghq.com"
      },
      {
       "name": "DD_PROCESS_AGENT_ENABLED",
       "value": "true",
      }
    ]
  )
}

module "datadog" {
  source = "github.com/borysbabii/terraform-aws-ecs-container-definition"
  // version = "0.56.0"

  container_name  = var.dd_container_name
  container_image = var.dd_container_image
  environment     = local.dd_env_vars
  secrets         = var.dd_secrets
  port_mappings   = var.dd_port_mappings

  docker_labels = merge({
    "traefik.enable" = "false"
  }, var.dd_docker_labels)

  container_cpu                = 10
  container_memory_reservation = 512

  mount_points = [
    {
      containerPath = "/var/run/docker.sock",
      sourceVolume = "docker_sock",
      readOnly = true
    },
    {
      containerPath = "/host/sys/fs/cgroup",
      sourceVolume = "cgroup",
      readOnly = true
    },
    {
      containerPath = "/host/proc",
      sourceVolume = "proc",
      readOnly = true
    },
  ]

  healthcheck = {
    retries = 3,
    command = ["CMD-SHELL","agent health"],
    timeout = 5,
    interval = 30,
    startPeriod = 15
  }


  log_configuration = {
    logDriver = "awslogs"
    options = {
      "awslogs-group"         = var.dd_awslogs_group
      "awslogs-region"        = var.awslogs_region
      "awslogs-stream-prefix" = var.awslogs_stream_prefix
    }
    secretOptions = null
  }
}

resource "aws_ecs_task_definition" "this" {
  family                   = local.family
  task_role_arn            = var.task_role_arn
  execution_role_arn       = var.exec_role_arn
  #network_mode             = "host"
  requires_compatibilities = ["EC2"]
  tags                     = var.tags

  container_definitions = module.datadog.json_map_encoded_list

  volume {
    host_path = "/var/run/docker.sock"
    name = "docker_sock"
  }

  volume {
    host_path = "/sys/fs/cgroup/"
    name = "cgroup"
  }

  volume {
    host_path = "/proc/"
    name = "proc"
  }

  lifecycle {
    create_before_destroy = true
  }
}

output "debug" {
  value = module.datadog.json_map_encoded_list
}
