locals {
  name   = "OpenVPN Gateway"
  region = "cn-north-1"

  user_data = <<-EOT
  #!/bin/bash
  echo "Hello Admin!"
  EOT

  tags = {
    owner   = "liuy@pingcap.com"
    usage   = "jsm-peering-to-ucloud"
    context = "jsm-customer-service-app"
  }
}

data "aws_ami" "amazon_linux" {
  most_recent = true
  owners      = ["amazon"]

  filter {
    name   = "name"
    values = ["amzn-ami-hvm-*-x86_64-gp2"]
  }
}

module "security_group" {
  source  = "terraform-aws-modules/security-group/aws"
  version = "~> 4.0"

  name        = local.name
  description = "Security group for EC2 instance of OpenVPN"
  vpc_id      = module.vpc.vpc_id

  ingress_cidr_blocks = ["0.0.0.0/0"]
  ingress_rules       = ["all-icmp"]
  ingress_with_cidr_blocks = [
    {
      from_port   = 3306
      to_port     = 3306
      protocol    = "tcp"
      description = "MySQL port"
      cidr_blocks = module.vpc.vpc_cidr_block
    },
    {
      from_port   = 1199
      to_port     = 1199
      protocol    = "tcp"
      description = "open-vpn ucloud"
      cidr_blocks = "117.50.84.111/32"
    },
    {
      from_port   = 1199
      to_port     = 1199
      protocol    = "tcp"
      description = "open-vpn ucloud new"
      cidr_blocks = "106.75.98.171/32"
    }
  ]
  egress_rules = ["all-all"]

  tags = local.tags
}

module "openvpn_ec2" {
  source = "terraform-aws-modules/ec2-instance/aws"

  name                        = local.name
  ami                         = "ami-0df628cd98c95235e"
  instance_type               = "t2.micro"
  availability_zone           = element(module.vpc.azs, 0)
  subnet_id                   = element(module.vpc.public_subnets, 0)
  vpc_security_group_ids      = [module.security_group.security_group_id]
  associate_public_ip_address = true
  user_data_base64            = base64encode(local.user_data)
  key_name                    = "openvpn-ec2-key"
  source_dest_check           = false

  enable_volume_tags = false
  root_block_device = [
    {
      encrypted   = true
      volume_type = "gp2"
      volume_size = 20
      tags = {
        owner = "liuy@pingcap.com"
        name  = "openvpn-ec2-root-block"
      }
    }
  ]

  tags = local.tags
}

resource "aws_route" "this" {
  count                  = length(module.vpc.private_route_table_ids)
  route_table_id         = module.vpc.private_route_table_ids[count.index]
  destination_cidr_block = "10.100.0.0/24"
  network_interface_id   = module.openvpn_ec2.primary_network_interface_id
}
