# EBS volumes ================================================================

resource "aws_ebs_volume" "this" {
  for_each = var.volumes

  availability_zone    = each.value.availability_zone
  size                 = each.value.size
  type                 = each.value.type
  iops                 = each.value.iops
  throughput           = each.value.throughput
  encrypted            = each.value.encrypted
  kms_key_id           = each.value.kms_key_id
  multi_attach_enabled = each.value.multi_attach_enabled
  snapshot_id          = each.value.snapshot_id
  final_snapshot       = each.value.final_snapshot

  tags = merge(local.tags, { Name = each.key })
}

# Volume attachments ---------------------------------------------------------

data "aws_instance" "target" {
  for_each = local.volumes_with_attachment

  filter {
    name   = "tag:Name"
    values = [each.value.instance_name]
  }
}

resource "aws_volume_attachment" "this" {
  for_each = local.volumes_with_attachment

  device_name  = each.value.device_name
  volume_id    = aws_ebs_volume.this[each.key].id
  instance_id  = data.aws_instance.target[each.key].id
  force_detach = each.value.force_detach
}

# DLM IAM role ===============================================================

data "aws_partition" "current" {}

resource "aws_iam_role" "dlm" {
  for_each = local.create_dlm_role ? { role = true } : {}

  name = "${var.dlm_policy_name}-role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { Service = "dlm.amazonaws.com" }
      Action    = "sts:AssumeRole"
    }]
  })

  tags = local.tags
}

resource "aws_iam_role_policy_attachment" "dlm" {
  for_each = local.create_dlm_role ? { role = true } : {}

  role       = aws_iam_role.dlm["role"].name
  policy_arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/service-role/AWSDataLifecycleManagerServiceRole"
}

# DLM snapshot lifecycle policy ==============================================

resource "aws_dlm_lifecycle_policy" "this" {
  for_each = var.snapshot_schedules

  description        = each.value.name
  execution_role_arn = local.dlm_role_arn
  state              = "ENABLED"

  policy_details {
    resource_types = ["VOLUME"]

    target_tags = each.value.target_tags

    schedule {
      name = each.value.name

      create_rule {
        interval      = each.value.interval
        interval_unit = each.value.interval_unit
        times         = each.value.times
      }

      retain_rule {
        count = each.value.retain_count
      }

      tags_to_add = merge(local.tags, { SnapshotCreator = "DLM" })

      copy_tags = true
    }
  }

  tags = local.tags

  depends_on = [aws_iam_role_policy_attachment.dlm]
}
