resource "aws_iam_policy" "mdradmin_tfstate_setup" {
  name        = "mdradmmin_tfstate_setup"
  path        = "/bootstrap/"
  description = "Gives MDRAdmin account rights needed to set up tfstate management"
  policy      = data.aws_iam_policy_document.mdradmin_tfstate_setup.json
}

data "aws_iam_policy_document" "mdradmin_tfstate_setup" {
  statement {
    sid = "DynamoDBTablesAndLocking"
    actions = [
      "dynamodb:*"
    ]
    resources = [
      "arn:${local.aws_partition}:dynamodb:${local.aws_region}:${local.aws_account}:table/${var.lock_table_name}"
    ]
    condition {
      test     = "BoolIfExists"
      variable = "aws:MultiFactorAuthPresent"
      values = [
        true
      ]
    }
  }

  statement {
    sid = "DynamoDBTablesAndLocking2"
    actions = [
      "dynamodb:ListTables"
    ]
    resources = [
      "arn:${local.aws_partition}:dynamodb:${local.aws_region}:${local.aws_account}:table/*"
    ]
    condition {
      test     = "BoolIfExists"
      variable = "aws:MultiFactorAuthPresent"
      values = [
        true
      ]
    }
  }

  statement {
    sid = "KMSKeyCreate"
    actions = [
      "kms:CreateAlias",
      "kms:CreateKey",
      "kms:List*",
      "kms:DeleteAlias",
      "kms:DeleteKey"
    ]

    # I wish I could scope this down to just specific keys
    # But I don't think it's possible
    resources = [
      "*"
    ]
    condition {
      test     = "BoolIfExists"
      variable = "aws:MultiFactorAuthPresent"
      values = [
        true
      ]
    }
  }
  statement {
    sid = "S3AllResources"
    actions = [ 
      "s3:HeadBucket" 
    ]
    resources = [
      "*"
    ]
    condition {
      test     = "BoolIfExists"
      variable = "aws:MultiFactorAuthPresent"
      values = [
        true
      ]
    }
  }
  statement {
    sid = "S3ManageStateBucket"
    actions = [
      "s3:CreateBucket",
      "s3:DeleteBucket",
      "s3:ListBucket",
      "s3:Get*",
      "s3:Put*"
    ]
    resources = [
      "arn:${local.aws_partition}:s3:::${var.bucket_name}"
    ]
    condition {
      test     = "BoolIfExists"
      variable = "aws:MultiFactorAuthPresent"
      values = [
        true
      ]
    }
  }
  statement {
    sid = "S3ObjectOperations"
    actions = [
      "s3:PutObject*",
      "s3:GetObject*",
      "s3:DeleteObject*"
    ]
    resources = [
      "arn:${local.aws_partition}:s3:::${var.bucket_name}/*"
    ]
    condition {
      test     = "BoolIfExists"
      variable = "aws:MultiFactorAuthPresent"
      values = [
        true
      ]
    }
  }
}
