resource "aws_vpc" "kubernetes_cluster" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_support   = true
  enable_dns_hostnames = true

  tags = {
    Name = "{{ cluster_name }}"
  }
}

resource "aws_subnet" "public" {
  vpc_id                  = aws_vpc.kubernetes_cluster.id
  cidr_block              = "10.0.0.0/24"
  map_public_ip_on_launch = true
  availability_zone       = "{{ availability_zone }}"

  tags = {
    Name = "{{ cluster_name }}_public"
  }
}

resource "aws_internet_gateway" "kubernetes_cluster" {
  vpc_id = aws_vpc.kubernetes_cluster.id

  tags = {
    Name = "{{ cluster_name }}_public"
  }
}

resource "aws_route_table" "public" {
  vpc_id = aws_vpc.kubernetes_cluster.id

  tags = {
    Name = "{{ cluster_name }}_public_route_table"
  }
}

resource "aws_route" "public" {
  route_table_id         = aws_route_table.public.id
  gateway_id             = aws_internet_gateway.kubernetes_cluster.id
  destination_cidr_block = "0.0.0.0/0"
}

resource "aws_route_table_association" "public" {
  subnet_id      = aws_subnet.public.id
  route_table_id = aws_route_table.public.id
}

module "internal_all_sg" {
  source      = "./security_group"
  name        = "internal_all_sg"
  vpc_id      = aws_vpc.kubernetes_cluster.id
  from_port   = "-1"
  to_port     = "-1"
  protocol    = "-1"
  cidr_blocks = [aws_vpc.kubernetes_cluster.cidr_block]
}

module "global_all_sg" {
  source      = "./security_group"
  name        = "global_all_sg"
  vpc_id      = aws_vpc.kubernetes_cluster.id
  from_port   = 0
  to_port     = 65535
  protocol    = "tcp"
  cidr_blocks = ["0.0.0.0/0"]
}

module "global_ssh_sg" {
  source      = "./security_group"
  name        = "global_ssh_sg"
  vpc_id      = aws_vpc.kubernetes_cluster.id
  from_port   = 22
  to_port     = 22
  protocol    = "tcp"
  cidr_blocks = ["0.0.0.0/0"]
}

{%- if -1 not in open_ports %}
{% for port in open_ports %}
module "global_{{ port }}_sg" {
  source      = "./security_group"
  name        = "global_{{ port }}_sg"
  vpc_id      = aws_vpc.kubernetes_cluster.id
  from_port   = {{ port }}
  to_port     = {{ port }}
  protocol    = "tcp"
  cidr_blocks = ["0.0.0.0/0"]
}
{% endfor %}
{% endif %}
