locals {
  name = "${var.env_prefix}-${var.project_group}-${var.project}"
  resourceRequirements = var.gpu_number == 0 ? [] : [
    {
      type  = "GPU"
      value = var.gpu_number
    }
  ]
  env_vars_from_map = [for k, v in var.env_vars_map : { "name" = k, "value" = v }]
}

resource "aws_batch_job_definition" "main" {
  name       = local.name
  type       = "container"
  parameters = var.parameters

  timeout {
    attempt_duration_seconds = var.timeout_seconds
  }

  retry_strategy {
    attempts = var.retry_attempts
  }

  container_properties = templatefile(
    "${path.module}/${var.containers_template}",
    {
      docker_image         = var.image
      command              = jsonencode(var.command)
      vcpus                = var.vcpus
      memory               = var.memory
      jobRoleArn           = var.job_role_arn
      env_vars             = jsonencode(concat(var.env_vars, local.env_vars_from_map))
      resourceRequirements = jsonencode(local.resourceRequirements)
    }
  )

  lifecycle {
    create_before_destroy = true
  }
}
