module "public_dns_record" {
  source = "../../submodules/dns/public_ALIAS_record"

  name = "keycloak.${var.dns_info["public"]["zone"]}"
  target_dns_name = aws_elb.external.dns_name
  target_zone_id  = aws_elb.external.zone_id
  dns_info = var.dns_info

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

resource "aws_elb" "external" {
  name = "keycloak-external-elb"
  subnets     = var.public_subnets
  security_groups  = [ aws_security_group.elb_external.id ]

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

  # We want client certs, so SSL must be terminated on the instance
  listener {
    instance_port      = 8443
    instance_protocol  = "TCP"
    lb_port            = 443
    lb_protocol        = "TCP"
    #ssl_certificate_id = aws_acm_certificate.cert.arn
  }

  listener {
    instance_port      = 80
    instance_protocol  = "HTTP"
    lb_port            = 8080
    lb_protocol        = "HTTP"
  }

  health_check {
    healthy_threshold   = 2
    unhealthy_threshold = 2
    timeout             = 3
    target              = "HTTPS:8443/"
    interval            = 10
  }

  cross_zone_load_balancing   = true
  idle_timeout                = 300
  connection_draining         = true
  connection_draining_timeout = 300

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

# Create a new load balancer attachment
resource "aws_elb_attachment" "external_attachment" {
  count    = var.keycloak_instance_count
  elb      = aws_elb.external.id
  instance = aws_instance.instance[count.index].id
}

# No stickiness on TCP
#resource "aws_lb_cookie_stickiness_policy" "external" {
#  name          = "Stickiness"
#  load_balancer = aws_elb.external.name
#  lb_port       = 443
#  cookie_expiration_period = 600
#}

# No policy on TCP
## Seems like there should be an easier way for terraform to assign the default policy, but
## this is how it's done according to https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/load_balancer_listener_policy
#resource "aws_load_balancer_policy" "elb_external_ssl_policy" {
#  load_balancer_name = aws_elb.external.name
#  policy_name        = "CopyOfELBSecurityPolicy-TLS-1-1-2017-01"
#  policy_type_name   = "SSLNegotiationPolicyType"
#
#  policy_attribute {
#    name  = "Reference-Security-Policy"
#    value = "ELBSecurityPolicy-TLS-1-1-2017-01" # ALBs have a (superior?) "ELBSecurityPolicy-FS-1-2-Res-2019-08", but this will have to do for ELB
#  }
#}
#
#resource "aws_load_balancer_listener_policy" "elb-external-listener-policies-443" {
#  load_balancer_name = aws_elb.external.name
#  load_balancer_port = 443
#
#  policy_names = [
#    aws_load_balancer_policy.elb_external_ssl_policy.policy_name
#  ]
#}

### Client Certificate Configuration
#
# No AWS LBs support client certificates, unfortunately.
