provider "aws" {
  region = "us-east-1"
}

provider "aws" {
  alias  = "eu-central"
  region = "eu-central-1"
}

# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "prod/phonofile-s3/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

# Assume role policy covering each role's service identifier
data "aws_iam_policy_document" "assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type = "Service"
      identifiers = [
        "s3.amazonaws.com",
      ]
    }
  }
}

# Replication role.
resource "aws_iam_role" "s3_replication_role" {
  name               = "S3-phonofile-replication-role"
  assume_role_policy = data.aws_iam_policy_document.assume_role_policy.json
}

data "aws_iam_policy_document" "s3_replication_policy" {
  statement {
    actions = [
      "s3:GetReplicationConfiguration",
      "s3:ListBucket"
    ]

    resources = [
      aws_s3_bucket.source_bucket.arn
    ]
  }

  statement {
    actions = [
      "s3:GetObjectVersion",
      "s3:GetObjectVersionAcl"
    ]

    resources = [
      "${aws_s3_bucket.source_bucket.arn}/*"
    ]
  }

  statement {
    actions = [
      "s3:ReplicateObject",
      "s3:ReplicateDelete"
    ]

    resources = [
      "${aws_s3_bucket.destination_bucket.arn}/*"
    ]
  }
}

resource "aws_iam_policy" "s3_replication_policy" {
  name   = "S3-phonofile-replication-policy"
  policy = data.aws_iam_policy_document.s3_replication_policy.json
}

resource "aws_iam_policy_attachment" "s3_replication_attachment" {
  name       = "S3-phonofile-replication-policy-attachment"
  roles      = [aws_iam_role.s3_replication_role.name]
  policy_arn = aws_iam_policy.s3_replication_policy.arn
}

resource "aws_s3_bucket" "destination_bucket" {
  provider = aws
  bucket   = "phonofile-assets-temp-us-east-1"
  acl      = "private"

  versioning {
    enabled = true
  }
}

resource "aws_s3_bucket" "source_bucket" {
  provider = aws.eu-central
  bucket   = "phonofile-assets-temp"
  acl      = "private"

  versioning {
    enabled = true
  }

  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        sse_algorithm = "AES256"
      }
    }
  }

  replication_configuration {
    role = aws_iam_role.s3_replication_role.arn

    rules {
      id     = aws_s3_bucket.destination_bucket.bucket
      prefix = ""
      status = "Enabled"

      destination {
        bucket        = aws_s3_bucket.destination_bucket.arn
        storage_class = "STANDARD"
      }
    }
  }

  tags = {
    environment = "prod"
    terraformed = "true"
  }
}
