# Nessus manager might need an NLB:
## untested, but i didn't want to mess with the certificate on the Nessus Manager. 
## I have a hunch that the agent is checking the CA of the certificate. 
## This nlb is specifically for LCP nodes to connect. 

module "public_dns_record_nessus-manager-nlb" {
  source = "../../../submodules/dns/public_ALIAS_record"

  name = "nessus-manager.${var.dns_info["public"]["zone"]}"
  target_dns_name = aws_lb.external.dns_name
  target_zone_id  = aws_lb.external.zone_id
  dns_info = var.dns_info

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

resource "aws_lb" "external" {
  name = "nessus-manager-external-nlb"
  load_balancer_type = "network"
  internal = false
  subnets = var.public_subnets

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

  enable_cross_zone_load_balancing = true
  idle_timeout                = 300

  tags = merge(var.standard_tags, var.tags)
}

resource "aws_lb_listener" "nlb_443" {
  load_balancer_arn = aws_lb.external.arn
  port              = "443"
  protocol          = "TCP"

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

resource "aws_lb_target_group" "external" {
  name     = "nessus-manager-external-nlb"
  port     = 8834
  protocol = "TCP"
  vpc_id   = var.vpc_id
  target_type = "instance"

  health_check {
    enabled = true
    #healthy_threshold   = 3
    #unhealthy_threshold = 2
    timeout = 10
    interval = 10
    #matcher = "200,302"
    path = "/"
    protocol = "HTTPS"
  }

  stickiness {
    enabled = true
    type = "source_ip" # only option for NLBs
  }
}

# Create a new load balancer attachment
resource "aws_lb_target_group_attachment" "external_attachment" {
  count = var.nessus_manager_count
  target_group_arn = aws_lb_target_group.external.arn
  target_id = aws_instance.nessus-manager-instance[count.index].id
}
