

data "aws_caller_identity" "current" {}
data "aws_region" "current" {}

data "aws_kms_key" "efs_encryption" {
  # default key for KMS encryption
  key_id = "arn:aws:kms:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:alias/aws/elasticfilesystem"
}

resource "aws_security_group" "efs_access" {
  name = "${var.name}-efs-access"
  tags = merge({
    "Name" = "${var.name}-efs-access"
  }, var.tags)

  vpc_id = var.vpc != "" ? var.vpc : aws_vpc.ad_hoc[0].id

  // allow SSH
  ingress {
    from_port = 22
    protocol = "tcp"
    to_port = 22
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port       = 0
    to_port         = 0
    protocol        = "-1"
    cidr_blocks     = ["0.0.0.0/0"]
  }
}

resource "aws_security_group" "efs_internal" {
  name        = "${var.name}-efs-internal"
  tags = merge({
    "Name" = "${var.name}-efs-internal"
  }, var.tags)

  vpc_id = var.vpc != "" ? var.vpc : aws_vpc.ad_hoc[0].id

  ingress {
    security_groups = concat(var.access_security_groups, [aws_security_group.efs_access.id])
    protocol  = "tcp"
    from_port = 2049
    to_port   = 2049
  }
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_efs_mount_target" "per_az" {
  count = length(data.aws_availability_zones.available.names)

  file_system_id  = aws_efs_file_system.main.id
  subnet_id       = aws_subnet.per_az[count.index].id
  security_groups = [aws_security_group.efs_internal.id]
}


resource "aws_efs_file_system" "main" {
  tags = merge({
    "Name" = "${var.name}-efs"
  }, var.tags)

  performance_mode = "generalPurpose"
  encrypted        = true
  kms_key_id       = data.aws_kms_key.efs_encryption.arn
  throughput_mode  = "bursting"
}
