provider "aws" {
  region = var.aws_region
}

# S3 backend
terraform {
  backend "s3" {
    bucket         = "orcd-terraform-state"
    key            = "prod/integrations/orcd-intralabel-ingest/terraform.tfstate"
    region         = "us-east-1"
    encrypt        = "true"
  }
}

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

    env                 = var.environment
    bucket_name         = var.bucket_name
    s3_read_only_policy = true
    application_family  = var.application_family

    apply_server_side_encryption_by_default = {

      sse_algorithm     = "AES256"
    }
}

resource "aws_iam_user" "iam_user" {
  name = "${var.environment}-orcd-intralabel-ingest"

  tags = {
    terraformed = true
  }
}

data "aws_iam_policy_document" "s3_read_write_policy" {
  statement {
    actions = [
      "s3:GetBucketLocation",
      "s3:GetObject",
      "s3:GetObject*",
      "s3:ListBucket",
      "s3:PutObject",
      "s3:PutObject*",
    ]

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

  statement {
    actions = [
      "s3:ListBucket",
    ]

    resources = [
      module.s3_bucket.s3_bucket_arn_output
    ]
  }

  statement {
    actions = [
      "s3:GetBucketLocation",
      "s3:ListAllMyBuckets"
    ]

    resources = [
      "*"
    ]
  }
}

# Create policy for read-write access to the S3 bucket
resource "aws_iam_policy" "s3_read_write_policy" {
  name   = "S3-${var.environment}-${var.bucket_name}-read-write-policy"
  policy = data.aws_iam_policy_document.s3_read_write_policy.json
}

resource "aws_iam_group_policy_attachment" "attach_rw_policy" {
  group      = "operations-group"
  policy_arn = aws_iam_policy.s3_read_write_policy.arn
}

resource "aws_iam_user_policy_attachment" "attach_rw_policy" {
  user = aws_iam_user.iam_user.name
  policy_arn = aws_iam_policy.s3_read_write_policy.arn
  }
