locals {
  enabled    = var.enabled ? "ENABLED" : "DISABLED"
  image_id   = var.custom_image_id == "" ? data.aws_ami.latest_ecs.id : var.custom_image_id
  name       = "${var.env_prefix}-${var.project_group}-${var.name}"
  disk1_iops = var.disk1_iops == 0 ? null : var.disk1_iops
  disk2_iops = var.disk2_iops == 0 ? null : var.disk2_iops

  user_data = <<DATA
Content-Type: multipart/mixed; boundary="==BOUNDARY=="
MIME-Version: 1.0

--==BOUNDARY==
Content-Type: text/cloud-boothook; charset="us-ascii"

# Set Docker daemon options
cloud-init-per once docker_options echo 'OPTIONS="--default-ulimit nofile=${var.container_ulimit_nofile} --storage-opt dm.basesize=${var.docker_pool_disk}G"' >> /etc/sysconfig/docker

--==BOUNDARY==
Content-Type: text/x-shellscript; charset="us-ascii"

#!/bin/bash
# Set any ECS agent configuration options
echo "ECS_CONTAINER_STOP_TIMEOUT=${var.ecs_container_stop_timeout}" >> /etc/ecs/ecs.config
yum update -y
service docker restart
start ecs

docker_status=$(service docker status)

if [[ "$docker_status" != *"running"* ]]; then
  # Print an error message to the cloud-init log
  echo "ERROR: The docker daemon is not running." >> /var/log/cloud-init-output.log

  # Stop the cloud-init service to prevent further script execution
  yum install unzip -y
  curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" -s
  unzip awscliv2.zip
  ./aws/install

  instance=$(curl http://169.254.169.254/latest/meta-data/instance-id)
  /usr/local/bin/aws autoscaling set-instance-health --instance-id $instance --health-status Unhealthy
fi


--==BOUNDARY==--
DATA
}

data "aws_ami" "latest_ecs" {
  most_recent = true
  owners      = ["591542846629"] # AWS

  filter {
    name   = "name"
    values = ["*amazon-ecs-optimized"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }
}

resource "aws_batch_compute_environment" "main" {
  name         = var.prefix ? null : local.name
  name_prefix  = var.prefix ? local.name : null
  service_role = var.batch_service_role
  state        = local.enabled
  type         = "MANAGED"

  compute_resources {
    type               = "EC2"
    instance_role      = var.instance_role
    instance_type      = var.instance_types
    max_vcpus          = var.max_vcpus
    desired_vcpus      = var.min_vcpus
    min_vcpus          = var.min_vcpus
    security_group_ids = var.security_groups
    subnets            = var.subnets

    launch_template {
      launch_template_name = aws_launch_template.this.name
      version              = aws_launch_template.this.latest_version
    }
  }

  lifecycle {
    ignore_changes        = [compute_resources[0].desired_vcpus]
    create_before_destroy = true
    replace_triggered_by  = [aws_launch_template.this.latest_version]
  }
}

resource "aws_launch_template" "this" {
  name = "${local.name}-batch-template"

  key_name      = var.ec2_key_pair
  image_id      = local.image_id
  ebs_optimized = true
  user_data     = base64encode(local.user_data)

  update_default_version = true

  block_device_mappings {
    device_name = "/dev/xvda"

    ebs {
      volume_size           = var.disk1_size
      volume_type           = var.disk1_type
      iops                  = var.disk1_iops
      encrypted             = var.kms_key_arn != "" ? true : false
      delete_on_termination = true
      kms_key_id            = var.kms_key_arn != "" ? var.kms_key_arn : null
    }
  }

  block_device_mappings {
    device_name = "/dev/xvdcz"

    ebs {
      volume_size           = var.disk2_size
      volume_type           = var.disk2_type
      iops                  = var.disk2_iops
      encrypted             = var.kms_key_arn != "" ? true : false
      delete_on_termination = true
      kms_key_id            = var.kms_key_arn != "" ? var.kms_key_arn : null
    }
  }

  tag_specifications {
    resource_type = "instance"
    tags = merge(
      var.common_tags,
      {
        SERVER_TYPE = "ECS"
      }
    )
  }

  tag_specifications {
    resource_type = "volume"
    tags          = var.common_tags
  }

  lifecycle {
    ignore_changes = [image_id] #[user_data]
  }
}
