# Rather than pass in the aws security group, we just look it up. This will
# probably be useful other places, as well.
data "aws_security_group" "typical-host" {
  name   = "typical-host"
  vpc_id = var.vpc_id
}

# Use the default EBS key
data "aws_kms_key" "ebs-key" {
  key_id = "alias/ebs_root_encrypt_decrypt"
}

resource "aws_instance" "ghe" {
  count                       = var.instance_count

  ami                         = aws_ami_copy.github.id
  instance_type               = var.instance_type
  subnet_id                   = var.private_subnets[count.index]
  vpc_security_group_ids      = [ data.aws_security_group.typical-host.id, aws_security_group.ghe_server.id ]
  associate_public_ip_address = false
  ebs_optimized               = true
  tenancy = "default"
  disable_api_termination = var.instance_termination_protection
  instance_initiated_shutdown_behavior = "stop"
  key_name = "msoc-build"
  monitoring = false
  iam_instance_profile = "msoc-default-instance-profile"
  
  # single space to disable default module behavior
  root_block_device {
      volume_size           = 200
      volume_type           = "gp3"
      iops                  = 3000
      delete_on_termination = true
      encrypted             = true
      kms_key_id            = data.aws_kms_key.ebs-key.arn
    } 

  ebs_block_device {
    # github data
    # Note: Not in AMI
    device_name = "/dev/xvdf"
    volume_size = var.github_data_volume_size
    delete_on_termination = true
    encrypted = true
    kms_key_id = data.aws_kms_key.ebs-key.arn
    volume_type = "gp3"
    iops = 3000
  }

  tags = merge( var.standard_tags, var.tags, { Name = format("%s-%s", "github-enterprise", count.index) })
  volume_tags = merge( var.standard_tags, var.tags, { Name = format("%s-%s", "github-enterprise", count.index) })
}

# Would need this a second time if count > 0
module "private_dns_record_ghe_backup_0" {
  source = "../../submodules/dns/private_A_record"

  name = format("%s-%s", "github-enterprise", 0)
  ip_addresses = [ aws_instance.ghe[0].private_ip ]
  dns_info = var.dns_info
  reverse_enabled = var.reverse_enabled

  providers = {
    aws.c2 = aws.c2
  }
}
