locals {
  service_name      = "com.amazonaws.${lower(var.region)}.${lower(var.service)}"
  vpce_service_name = "com.amazonaws.vpce.${lower(var.region)}.${lower(var.service)}"

  policy             = var.policy == "" ? null : var.policy
  security_group_ids = (var.vpc_endpoint_type == "Interface") ? concat([aws_security_group.gsirt_endpoint[0].id], var.security_group_ids) : []
}

resource "aws_vpc_endpoint" "main" {
  vpc_id             = var.vpc_id
  service_name       = (var.vpc_endpoint_type == "Interface") ? local.vpce_service_name : local.service_name
  policy             = local.policy
  vpc_endpoint_type  = var.vpc_endpoint_type
  security_group_ids = local.security_group_ids
  subnet_ids         = var.subnet_ids
  tags               = var.common_tags
}

resource "aws_vpc_endpoint_route_table_association" "main" {
  count           = length(var.route_tables)
  vpc_endpoint_id = aws_vpc_endpoint.main.id
  route_table_id  = var.route_tables[count.index]
}

resource "aws_security_group" "gsirt_endpoint" {
  count       = (var.vpc_endpoint_type == "Interface") ? 1 : 0
  description = "Security group used by the GSIRT-Endpoint"
  vpc_id      = var.vpc_id

  ingress {
    description = "Syslog TCP"
    from_port   = 514
    to_port     = 514
    protocol    = "tcp"
    cidr_blocks = ["10.${var.cidr_second_octet}.0.0/16"]
  }

  ingress {
    description = "Used to send events from a Splunk forwarder to a Splunk listener using encryption."
    from_port   = 9998
    to_port     = 9998
    protocol    = "tcp"
    cidr_blocks = ["10.${var.cidr_second_octet}.0.0/16"]
  }

  ingress {
    description = "Splunk REST API endpoint. This port is NOT used for any forwarding or indexing."
    from_port   = 8089
    to_port     = 8089
    protocol    = "tcp"
    cidr_blocks = ["10.${var.cidr_second_octet}.0.0/16"]
  }

  egress {
    description = "Allow all outbound traffic."
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = merge(
    var.common_tags,
    {
      Name             = "gsirt_endpint",
      "eiso-exception" = "aws.08.30",
    }
  )
}
