resource "aws_security_group" "interconnects_sg" {
  name        = "interconnects_sg"
  description = "Security Rules Specific to XDR interconnects"
  vpc_id      = var.security_vpc

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

resource "aws_security_group_rule" "trusted_ssh" {
  type              = "ingress"
  from_port         = 22
  to_port           = 22
  protocol          = "tcp"
  cidr_blocks       = var.trusted_ips
  security_group_id = aws_security_group.interconnects_sg.id
}

resource "aws_security_group_rule" "bgp_ingress" {
  type              = "ingress"
  from_port         = 179
  to_port           = 179
  protocol          = "tcp"
  cidr_blocks       = [ var.security_vpc_cidr ]
  security_group_id = aws_security_group.interconnects_sg.id
}

resource "aws_security_group_rule" "ipsec_l2tp_ingress" {
  type              = "ingress"
  from_port         = 1701
  to_port           = 1701
  protocol          = "udp"
  cidr_blocks       = [ "0.0.0.0/0" ]
  security_group_id = aws_security_group.interconnects_sg.id
}

resource "aws_security_group_rule" "ipsec_ike_ingress" {
  type              = "ingress"
  from_port         = 500
  to_port           = 500
  protocol          = "udp"
  cidr_blocks       = [ "0.0.0.0/0" ]
  security_group_id = aws_security_group.interconnects_sg.id
}

resource "aws_security_group_rule" "ipsec_ike_nat_t_ingress" {
  type              = "ingress"
  from_port         = 4500
  to_port           = 4500
  protocol          = "udp"
  cidr_blocks       = [ "0.0.0.0/0" ]
  security_group_id = aws_security_group.interconnects_sg.id
}

resource "aws_security_group_rule" "ipsec_egress" {
  type              = "egress"
  from_port         = 0 # all ports
  to_port           = 0 # all ports
  protocol          = "all"
  cidr_blocks       = [ "0.0.0.0/0" ]
  security_group_id = aws_security_group.interconnects_sg.id
}
