provider "aws" {
  region = var.region
}

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

data "aws_caller_identity" "current" {}

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

  application_family  = var.application_family
  env                 = var.environment
  custom_bucket_name  = "orcd-mobile-binaries"
  bucket_name         = "orcd-mobile-binaries"
  s3_read_only_policy = true

  apply_server_side_encryption_by_default = {
    sse_algorithm = "AES256"
  }

  lifecycle_rules_options_noncurrent_version_expiration = [
    {
      prefix  = ""
      enabled = true
      days    = 30
    }
  ]

  lifecycle_rules_options_current_version_expiration = [
    {
      prefix  = ""
      enabled = true
      days    = 90
    }
  ]

  lifecycle_rules_abort_incomplete_multipart_upload_days = [
    {
      prefix  = ""
      enabled = true
      days    = 7
    }
  ]
}

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

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

  apply_server_side_encryption_by_default = {

    sse_algorithm = "AES256"
  }

  lifecycle_rules_options_noncurrent_version_expiration = [
    {
      prefix  = ""
      enabled = true
      days    = 30
    }
  ]

  lifecycle_rules_options_current_version_expiration = [
    {
      prefix  = ""
      enabled = true
      days    = 90
    }
  ]

  lifecycle_rules_abort_incomplete_multipart_upload_days = [
    {
      prefix  = ""
      enabled = true
      days    = 7
    }
  ]
}

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

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

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

    resources = [
      module.mobile_binaries_s3_bucket.s3_bucket_arn_output,
      module.orcd_mobile_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.service_name}-read-write-policy"
  policy = data.aws_iam_policy_document.orcd_mobile_s3_bucket_read_write_policy.json
}
