#------------------------------------------------------------------------------
# An external NLB for the indexers for splunk-2-splunk
#------------------------------------------------------------------------------
resource "aws_eip" "nlb" {
  count = "3"

  vpc  = true
  tags = merge(var.standard_tags, var.tags, map("Name","${var.prefix}-nlb" ))
}

module "public_dns_record_nlb" {
  source = "../../../submodules/dns/public_A_record"

  name = "${var.prefix}-splunk-indexers"
  ip_addresses = aws_eip.nlb.*.public_ip
  dns_info = var.dns_info

  providers = {
    aws.mdr-common-services-commercial = aws.mdr-common-services-commercial
  }
}

resource "aws_lb" "nlb" {
  tags               = merge(var.standard_tags, var.tags, map("Name","${var.prefix}-splunk-indexers-nlb" ))
  name               = "${var.prefix}-splunk-indexers-nlb"
  internal           = false
  load_balancer_type = "network"
  #subnets            = data.terraform_remote_state.infra.public_subnets

  subnet_mapping {
    subnet_id = element(var.public_subnets,0)
    allocation_id = element(aws_eip.nlb.*.id,0)
  }

  subnet_mapping {
    subnet_id = element(var.public_subnets,1)
    allocation_id = element(aws_eip.nlb.*.id,1)
  }

  subnet_mapping {
    subnet_id = element(var.public_subnets,2)
    allocation_id = element(aws_eip.nlb.*.id,2)
  }

  access_logs {
    bucket  = "xdr-elb-${ var.environment }"
    enabled = true
  }
}

resource "aws_lb_target_group" "nlb_targets" {
  name     = "${var.prefix}-nlb-targets"
  port     = 9998
  protocol = "TCP"
  vpc_id   = var.vpc_id
}

resource "aws_autoscaling_attachment" "nlb_asg_attachments" {
  for_each = toset([ module.indexer0.asg_name[0], module.indexer1.asg_name[0], module.indexer2.asg_name[0] ])
  alb_target_group_arn   = aws_lb_target_group.nlb_targets.arn
  autoscaling_group_name = each.key
}

resource "aws_lb_listener" "nlb_targets" {
  load_balancer_arn = aws_lb.nlb.arn
  port              = 9998
  protocol          = "TCP"

  default_action {
    target_group_arn = aws_lb_target_group.nlb_targets.arn
    type             = "forward"
  }
}
