provider "aws" {
  region = var.aws_region
}

provider "aws" {
  region = var.aws_region
  alias  = "dev"
}

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

data "aws_caller_identity" "current" {}

module "vpc_info" {
  source = "git@github.com:theorchard/terraform-vpc-info.git?ref=3.1.0"

  environment = var.environment
}

data "aws_route53_zone" "route53_zone" {
  name = "${var.environment}.theorchard.io"
}

data "aws_acm_certificate" "certificate" {
  domain      = "*.dev.theorchard.io"
  statuses    = ["ISSUED"]
  most_recent = true
}

# Create efs file system for shared mounts
module "efs_volume" {
  source = "git@github.com:theorchard/terraform-efs.git//?ref=4.0.1"

  providers = {
    aws.dns = aws
  }

  environment              = var.environment
  service_name             = var.service_name
  application_family       = var.application_family
  vpc_id                   = module.vpc_info.vpc_id
  subnet_ids               = module.vpc_info.default_private_subnet_ids
  owner_gid                = "48"
  owner_uid                = "48"
  access_point_permissions = "700"
}
resource "aws_iam_user" "stripo_service" {
  name          = "${var.environment}-stripo-service"
  force_destroy = true

  tags = {
    environment  = var.environment
    service_name = var.service_name
    role         = "service-user"
  }
}

resource "aws_iam_user_policy_attachment" "stripo_service_attachment" {
  user       = aws_iam_user.stripo_service.name
  policy_arn = aws_iam_policy.s3_readwrite_policy.arn
}

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

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

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

    resources = [
      module.s3_bucket.s3_bucket_arn_output
    ]
  }

  statement {
    actions = [
      "kms:GenerateDataKey"
    ]

    resources = [
      module.s3_bucket.s3_kms_encryption_key_arn_output
    ]
  }
}

resource "aws_iam_policy" "s3_readwrite_policy" {
  name   = "S3-${var.environment}-${var.service_name}-RW"
  policy = data.aws_iam_policy_document.s3_readwrite_policy.json
}
