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_name
}

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     = "prod/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.1.0"

  environment = var.environment
}

data "aws_acm_certificate" "theorchard_com" {
  domain   = "*.theorchard.com"
  statuses = ["ISSUED"]
}

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"]
    }
  }
}

module "ows_legacy_images_waf" {
  source            = "git@github.com:theorchard/terraform-aws-waf.git//?ref=2.0.1"
  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",
  ]
}

# Create WAF for public service
module "ows_legacy_images_public_waf" {
  source            = "git@github.com:theorchard/terraform-aws-waf.git//?ref=2.0.1"
  environment       = var.environment
  service_name      = "${var.service_name}-public"
  aws_region        = var.aws_region
  count_waf_enabled = false
  block_waf_enabled = true
  excluded_rules = [
    "CrossSiteScripting_BODY",
    "NoUserAgent_HEADER",
    "SizeRestrictions_BODY",
    "GenericLFI_BODY",
  ]
}

module "ows_legacy_images_owsrequest" {
  source           = "git@github.com:theorchard/terraform-owsrequest.git//?ref=1.1.0"
  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"
  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"

  providers = {
    aws.dns = aws.networking
  }

}

# 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"
}

# This rule will allow the fargate security group to acess the EFS filesystem
resource "aws_security_group_rule" "allow_efs_public_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_public_fargate_environment.fargate_security_group_id
  type                     = "ingress"
}

module "ows_legacy_images_fargate_environment" {
  source = "git@github.com:theorchard/terraform-fargate.git//?ref=5.6.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                                 = 1024
  task_memory                              = 2048
  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
  # ACM certificate id for theorchard.com
  https_listener_certificate_id = split("/", data.aws_acm_certificate.theorchard_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
    },
  ]

  # For TF 13+
  # depends_on = [module.ows_legacy_images_waf]
}

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

  providers = {
    aws.dns = aws.networking
  }


  environment                              = var.environment
  non_ecr_image                            = "${data.aws_caller_identity.current.account_id}.dkr.ecr.${var.aws_region}.amazonaws.com/${var.service_name}:latest"
  service_name                             = "${var.service_name}-public"
  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                                 = 1024
  task_memory                              = 2048
  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_public_subnet_ids
  load_balancer_is_internal                = false
  custom_waf_arn                           = module.ows_legacy_images_public_waf.waf_blocking_arn_output
  # ACM certificate id for theorchard.com
  https_listener_certificate_id = split("/", data.aws_acm_certificate.theorchard_com.arn)[1]
  # Only allow access from Cloudflare IPs
  prod_https_listener_allow_cidr_blocks = [
    "173.245.48.0/20",
    "103.21.244.0/22",
    "103.22.200.0/22",
    "103.31.4.0/22",
    "141.101.64.0/18",
    "108.162.192.0/18",
    "190.93.240.0/20",
    "188.114.96.0/20",
    "197.234.240.0/22",
    "198.41.128.0/17",
    "162.158.0.0/15",
    "172.64.0.0/13",
    "131.0.72.0/22",
    "104.16.0.0/13",
    "104.24.0.0/14",
  ]
  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}-public"
      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}-public"
      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
    },
  ]

  # For TF 13+
  # depends_on = [module.ows_legacy_images_waf]
}


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

  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
}

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

  environment        = var.environment
  environment_type   = "fargate"
  service_name       = "${var.service_name}-public"
  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
}
