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

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

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

# TODO
# networking
# IAM
# task def
locals {
  user_data = <<DATA
#!/bin/bash
echo "ECS_CLUSTER=${aws_ecs_cluster.this.name}" >> /etc/ecs/ecs.config
DATA
}

resource "aws_launch_template" "this" {
  name_prefix            = "${local.name_prefix}-ecs-ec2-poc"
  image_id               = data.aws_ami.latest_ecs.id
  instance_type          = "m6in.xlarge"
  key_name               = local.ec2_key_pair
  ebs_optimized          = true
  user_data              = base64encode(local.user_data)
  vpc_security_group_ids = [data.aws_security_group.batch.id, data.aws_security_group.ssh.id]

  iam_instance_profile {
    name = data.aws_iam_instance_profile.ecs_instance.name
  }


  block_device_mappings {
    device_name = "/dev/xvda"

    ebs {
      volume_size           = 8
      volume_type           = "gp3"
      encrypted             = true
      delete_on_termination = true
      kms_key_id            = data.aws_kms_alias.default_ebs.target_key_arn
    }
  }

  block_device_mappings {
    device_name = "/dev/xvdcz"

    ebs {
      volume_size           = 50
      volume_type           = "gp3"
      encrypted             = true
      delete_on_termination = true
      kms_key_id            = data.aws_kms_alias.default_ebs.target_key_arn
    }
  }

  tag_specifications {
    resource_type = "instance"
    tags = merge(local.common_tags,
      {
        "service"                  = "EC2",
        "plat_env_project_service" = "${local.aggregated_tag}_EC2"
    })
  }

  tag_specifications {
    resource_type = "volume"
    tags = merge(local.common_tags,
      {
        "service"                  = "EC2",
        "plat_env_project_service" = "${local.aggregated_tag}_EC2"
    })
  }
}

resource "aws_autoscaling_group" "this" {
  #availability_zones = ["us-east-1a"]
  desired_capacity      = 1
  max_size              = 1
  min_size              = 1
  vpc_zone_identifier   = data.aws_subnets.private_subnets.ids
  protect_from_scale_in = true

  launch_template {
    id      = aws_launch_template.this.id
    version = "$Latest"
  }

  tag {
    key                 = "AmazonECSManaged"
    value               = true
    propagate_at_launch = true
  }
}
