module "default_tags" {
  source             = "git@github.com:theorchard/terraform-default-tags.git//?ref=2.0.0"
  environment        = var.environment
  application_family = var.application_family
  service_name       = var.service_name
  team_name          = var.team
}

provider "aws" {
  region = var.aws_region

  default_tags {
    tags = module.default_tags.tags
  }
}

provider "aws" {
  region  = var.aws_region
  alias   = "networking"
  profile = "networking"

  default_tags {
    tags = module.default_tags.tags
  }
}


# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "qa/ows-legacy-images/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.0.2"

  environment = var.environment
}

data "aws_acm_certificate" "qaorch_com" {
  domain      = "*.qaorch.com"
  types       = ["AMAZON_ISSUED"]
  most_recent = true
}

data "aws_route53_zone" "route53_zone" {
  name = "theorchard.io"
}

data "aws_iam_policy_document" "assume_role_policy_document" {
  statement {
    effect  = "Allow"
    actions = ["sts:AssumeRole"]

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

data "aws_s3_bucket" "logging_bucket_waf" {
  bucket = "aws-waf-logs-prod-tf-orcd-bucket"
}

# Create KMS key for the EFS backup vault
resource "aws_kms_key" "ows_legacy_images_kms_key" {
  description             = "${var.environment}-${var.service_name}-efs"
  enable_key_rotation     = true
  deletion_window_in_days = 30

  tags = {
    environment        = var.environment
    service_name       = var.service_name
    application_family = var.application_family
    terraformed        = true
  }
}

resource "aws_kms_alias" "ows_legacy_images_kms_alias" {
  name          = "alias/${var.environment}-${var.service_name}-efs"
  target_key_id = aws_kms_key.ows_legacy_images_kms_key.key_id
}

data "aws_iam_policy_document" "kms_decryption_policy" {
  statement {
    actions = [
      "kms:Decrypt",
      "kms:DescribeKey",
    ]

    resources = [
      aws_kms_key.ows_legacy_images_kms_key.arn,
    ]
  }
}

# Create KMS policy
resource "aws_iam_policy" "ows_legacy_images_kms_policy" {
  name   = "KMS-${var.environment}-${var.service_name}-policy"
  policy = data.aws_iam_policy_document.kms_decryption_policy.json

  tags = {
    environment        = var.environment
    service_name       = var.service_name
    application_family = var.application_family
    terraformed        = true
  }
}

module "ows_legacy_images_waf" {
  source            = "git@github.com:theorchard/terraform-aws-waf.git//?ref=1.5.0"
  environment       = var.environment
  service_name      = var.service_name
  aws_region        = var.aws_region
  count_waf_enabled = false
  block_waf_enabled = true
  excluded_rules = [
    "GenericRFI_BODY",
    "CrossSiteScripting_BODY",
    "NoUserAgent_HEADER",
    "SizeRestrictions_BODY",
    "GenericLFI_BODY",
    "Log4JRCE",
  ]

  logging_config_default_destination = data.aws_s3_bucket.logging_bucket_waf.arn
}

module "ows_legacy_images_owsrequest" {
  source           = "git@github.com:theorchard/terraform-owsrequest.git//?ref=1.0.1"
  environment_name = var.environment
  service_name     = var.service_name
}

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

  providers = {
    aws.dns = aws.networking
  }

  application_family       = var.application_family
  environment              = var.environment
  service_name             = var.service_name
  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"
}

# This rule will allow the fargate security group to acess the EFS filesystem
resource "aws_security_group_rule" "allow_efs_sg_inbound" {
  from_port                = 2049
  to_port                  = 2049
  protocol                 = "tcp"
  security_group_id        = module.efs_volume.efs_security_group_id_output
  source_security_group_id = module.ows_legacy_images_fargate_environment.fargate_security_group_id
  type                     = "ingress"
}

module "ows_legacy_images_fargate_environment" {
  source = "git@github.com:theorchard/terraform-fargate.git//?ref=5.5.1"

  providers = {
    aws.dns = aws.networking
  }

  environment                              = var.environment
  service_name                             = var.service_name
  aws_region                               = var.aws_region
  application_family                       = var.application_family
  service_platform_version                 = "1.4.0"
  desired_task_count                       = 2
  minimum_capacity                         = 2
  maximum_capacity                         = 4
  task_cpu                                 = 512
  task_memory                              = 1024
  container_port                           = 80
  health_check_grace_period_seconds        = 120
  container_start_period_seconds           = 120
  health_check_path                        = "/index.php"
  route53_zone_id                          = data.aws_route53_zone.route53_zone.zone_id
  load_balancer_access_logs_s3_bucket_name = "orch-elb-logs"
  vpc_id                                   = module.vpc_info.vpc_id
  fargate_service_subnets                  = module.vpc_info.default_private_subnet_ids
  load_balancer_subnets                    = module.vpc_info.default_private_subnet_ids
  custom_waf_arn                           = module.ows_legacy_images_waf.waf_blocking_arn_output
  https_listener_certificate_id            = split("/", data.aws_acm_certificate.qaorch_com.arn)[1]

  iam_managed_policy_attachments = [
    module.efs_volume.efs_iam_policy_arn_output,
    module.ows_legacy_images_owsrequest.policy_arn_output,
  ]
  docker_volumes = [
    {
      name            = "${var.environment}-${var.service_name}"
      file_system_id  = module.efs_volume.efs_file_system_id_output
      access_point_id = module.efs_volume.efs_access_point_id_output
    }
  ]
  docker_volume_mount_points = [
    {
      source_volume  = "${var.environment}-${var.service_name}"
      container_path = var.efs_volume_container_path
    }
  ]

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      DD_SERVICE_NAME = "${var.environment}-${var.service_name}"
    },
    {
      DD_TRACE_ANALYTICS_ENABLED = "true"
    },
    {
      DD_TRACE_APP_NAME = "${var.environment}-${var.service_name}"
    },
    {
      DD_TRACE_GLOBAL_TAGS = "env:${var.environment}-${var.service_name}"
    },
    {
      AWS_REGION = var.aws_region
    },
    {
      PHP_DISPLAY_ERRORS = "false"
    },
    {
      PHP_SESSION_COOKIE_SECURE = "1"
    },
    {
      PHP_SESSION_COOKIE_HTTPONLY = "1"
    },
    {
      EFS_VOLUME_CONTAINER_PATH = var.efs_volume_container_path
    },
  ]
}

module "ows_legacy_images_fargate_service_dashboard" {
  source = "git@github.com:theorchard/terraform-datadog.git//modules/service?ref=6.10.7"

  environment        = var.environment
  environment_type   = "fargate"
  service_name       = var.service_name
  application_family = var.application_family

  service_5xx_monitor_enabled   = false
  healthy_tasks_monitor_enabled = false
  service_cpu_monitor_enabled   = false

  notification_endpoints            = var.notification_endpoints
  escalation_notification_endpoints = var.escalation_notification_endpoints
}
