# Get an existing vpc id
data "aws_vpc" "this" {
  id = var.vpc_id
}

# Get account information
data "aws_caller_identity" "current" {
}

# Get an AMI id
data "aws_ami" "sftp" {
  most_recent = true
  owners = [
    "679593333241",
  ]
  filter {
    name = "virtualization-type"
    values = [
      "hvm",
    ]
  }
  filter {
    name = "product-code"
    values = [
      "aw0evgkw8e5c1q413zgy5pjce",
    ]
  }
}

# IAM policy document for ec2 instance's role within ASG
data "aws_iam_policy_document" "instance-assume-role-policy" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["ec2.amazonaws.com"]
    }
  }
}

resource "aws_iam_role" "sftp_role" {
  name               = "${var.environment}-${var.service_name}-service-role"
  assume_role_policy = data.aws_iam_policy_document.instance-assume-role-policy.json
}

resource "aws_lb" "sftp_elb" {
  name                             = "${var.environment}-${var.service_name}-elb"
  internal                         = var.elb_scheme
  load_balancer_type               = "network"
  subnets                          = var.elb_vpc_subnet_ids
  enable_cross_zone_load_balancing = true

  access_logs {
    bucket  = var.bucket_name
    prefix  = "${var.environment}-${var.service_name}-elb"
    enabled = true
  }

  tags = {
    Name         = "${var.environment}-${var.service_name}-elb"
    environment  = var.environment
    service_name = var.service_name
    terraformed  = true
  }
}

resource "aws_lb_target_group" "sftp_target_group" {
  name        = "${var.environment}-${var.service_name}-target-group"
  port        = 22
  protocol    = "TCP"
  vpc_id      = var.vpc_id
  target_type = "instance"

  tags = {
    Name         = "${var.environment}-${var.service_name}-target-group"
    environment  = var.environment
    service_name = var.service_name
    terraformed  = true
  }
}

resource "aws_lb_listener" "sftp_elb_listener" {
  load_balancer_arn = aws_lb.sftp_elb.arn
  port              = "22"
  protocol          = "TCP"

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.sftp_target_group.arn
  }
}

# A security group for the ELB
# It should be accesible within corporate network
resource "aws_security_group" "elb-sg" {
  name        = "${var.environment}-${var.service_name}-elb-sg"
  description = "SG for ${var.environment}-${var.service_name} Load balancer"
  vpc_id      = var.vpc_id

  # SSH access
  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = var.aws_elb_access_ips
  }

  # Outbound internet access
  egress {
    from_port = 22
    to_port   = 22
    protocol  = "tcp"
    cidr_blocks = [
      "0.0.0.0/0",
    ]
  }

  tags = {
    terraformed  = true
    environment  = var.environment
    service_name = var.service_name
  }
}

# Security group to access the instances from ELB
resource "aws_security_group" "asg-sg" {
  name        = "${var.environment}-${var.service_name}-asg"
  description = "AWS Security group for ${var.environment}-${var.service_name} ASG instances"
  vpc_id      = var.vpc_id

  # SSH access from ELB security group
  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = var.aws_asg_access_ips
    security_groups = [
      aws_security_group.elb-sg.id,
    ]
  }

  # outbound internet access
  egress {
    from_port = 0
    to_port   = 0
    protocol  = "-1"
    cidr_blocks = [
      "0.0.0.0/0",
    ]
  }

  tags = {
    terraformed  = true
    environment  = var.environment
    service_name = var.service_name
  }
}

# Launch configuration
resource "aws_launch_configuration" "launch-config" {
  name_prefix                 = "${var.environment}-${var.service_name}-lc-"
  image_id                    = data.aws_ami.sftp.id
  instance_type               = var.aws_instance_type
  associate_public_ip_address = false
  iam_instance_profile        = aws_iam_instance_profile.sftp_profile.name

  security_groups = [aws_security_group.asg-sg.id]
  key_name        = var.aws_key_name
  user_data       = var.user_data

  root_block_device {
    volume_type = var.volume_type
    volume_size = var.aws_volume_size
  }
  lifecycle {
    create_before_destroy = true
  }
}

# Auto scaling group
resource "aws_autoscaling_group" "asg" {
  name                      = "${var.environment}-${var.service_name}"
  availability_zones        = var.az
  max_size                  = var.aws_asg_max_instance
  min_size                  = var.aws_asg_min_instance
  desired_capacity          = var.aws_asg_desire_instance
  health_check_type         = "ELB"
  health_check_grace_period = 1200
  launch_configuration      = aws_launch_configuration.launch-config.name
  target_group_arns         = [aws_lb_target_group.sftp_target_group.arn]

  # Instances must be in same AZ as ELB
  vpc_zone_identifier = var.asg_vpc_subnet_ids

  tags = [
    {
      key                 = "Name"
      value               = "${var.environment}-${var.service_name}"
      propagate_at_launch = true
    },
    {
      key                 = "environment"
      value               = var.environment
      propagate_at_launch = true
    },
    {
      key                 = "service_name"
      value               = var.service_name
      propagate_at_launch = true
    },
  ]

  lifecycle {
    create_before_destroy = true
  }
}

resource "aws_route53_record" "dns" {
  zone_id = var.aws_route53_params["zone_id"]
  name    = "${var.environment}-${var.service_name}"
  type    = "CNAME"
  records = [aws_lb.sftp_elb.dns_name]
  ttl     = "60"
}

resource "aws_iam_instance_profile" "sftp_profile" {
  name       = "${var.environment}-${var.service_name}-instance-profile"
  role       = aws_iam_role.sftp_role.name
  depends_on = [aws_iam_role.sftp_role]
}

