locals {
  organization_id = "o-bqioddgr91"
  organization_units = [
    "ou-ax9e-vu43qt3i", // The Orchard OU
  ]
}

module "cookbook_storage_bucket" {
  source = "git@github.com:theorchard/terraform-s3.git//modules/s3_bucket?ref=3.14.1"

  env                = var.environment
  bucket_name        = "${var.service_name}-cookbook-storage"
  application_family = var.application_family

  apply_server_side_encryption_by_default = {
    sse_algorithm = "AES256"
  }
}

data "aws_iam_policy_document" "secrets_bucket_policy" {
  statement {
    sid = "AllowOrganizationListBucket"

    principals {
      type        = "*"
      identifiers = ["*"]
    }

    actions = [
      "s3:ListBucket",
    ]

    resources = [
      module.secrets_bucket.s3_bucket_arn_output,
    ]

    condition {
      test     = "ForAnyValue:StringLike"
      variable = "aws:PrincipalOrgPaths"
      values   = formatlist("${local.organization_id}/*/%s/*", local.organization_units)
    }
  }

  statement {
    sid = "AllowOrganizationGetObject"

    principals {
      type        = "*"
      identifiers = ["*"]
    }

    actions = [
      "s3:GetObject",
    ]

    resources = [
      "${module.secrets_bucket.s3_bucket_arn_output}/*",
    ]

    condition {
      test     = "ForAnyValue:StringLike"
      variable = "aws:PrincipalOrgPaths"
      values   = formatlist("${local.organization_id}/*/%s/*", local.organization_units)
    }
  }
}

module "secrets_bucket" {
  source = "git@github.com:theorchard/terraform-s3.git//modules/s3_bucket?ref=3.14.1"

  env                = var.environment
  bucket_name        = "${var.service_name}-secrets"
  application_family = var.application_family

  apply_server_side_encryption_by_default = {
    sse_algorithm = "AES256"
  }

  bucket_policy_overrides = [
    data.aws_iam_policy_document.secrets_bucket_policy.json
  ]
}

resource "aws_iam_user" "chef_server_user" {
  name = "${var.environment}-${var.service_name}"

  tags = {
    role = "service-user"
  }
}

module "s3_cookbook_storage_read_write_policy" {
  source = "git@github.com:theorchard/terraform-iam-policy-templates.git//documents/s3/buckets_with_prefixes?ref=0.4.0"

  buckets = [{
    bucket = module.cookbook_storage_bucket.s3_bucket_name_output
  }]
  action_types = ["read", "write"]
}

resource "aws_iam_user_policy" "s3_read_write_policy" {
  name   = "S3-${var.environment}-${var.service_name}-RW"
  policy = module.s3_cookbook_storage_read_write_policy.policy.json
  user   = aws_iam_user.chef_server_user.name
}

module "s3_secrets_read_write_policy" {
  source = "git@github.com:theorchard/terraform-iam-policy-templates.git//documents/s3/buckets_with_prefixes?ref=0.4.0"

  buckets = [{
    bucket = module.secrets_bucket.s3_bucket_name_output
  }]

  action_types = ["read", "write"]
}

resource "aws_iam_policy" "s3_secrets_read_write_policy" {
  name   = "S3-${module.secrets_bucket.s3_bucket_name_output}-RW"
  policy = module.s3_secrets_read_write_policy.policy.json
}
