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/vapi/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

data "aws_iam_user" "user" {
  user_name = "${var.environment}-${var.service_name}"
}

data "aws_iam_policy" "ows_machine_to_machine_policy" {
  name = "SecretsManager-${var.environment}-ows-machine-to-machine-policy"
}

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" "zone" {
  name         = "theorchard.io."
  private_zone = false
}

module "vapi-data-cache" {
  # checkov:skip=CKV_AWS_30:ElastiCache encryption in transit requires client library update.
  # checkov:skip=CKV_AWS_31:ElastiCache encryption in transit requires client library update.
  source = "git@github.com:theorchard/terraform-elasticache.git//?ref=3.1.1"

  providers = {
    aws.dns = aws.networking
  }

  environment                      = var.environment
  service_name                     = "${var.service_name}-data-cache"
  cache_parameter_group_name       = "default.redis7"
  redis_engine_version             = "7.1"
  application_family               = var.application_family
  cache_engine                     = "redis"
  cache_node_type                  = "cache.t4g.small"
  cache_subnet_group_name          = "${var.environment}-elasticache-subnet-group"
  cache_transit_encryption_enabled = false
  route53_zone_id                  = data.aws_route53_zone.zone.zone_id
  vpc_id                           = module.vpc_info.vpc_id
  additional_cidr_blocks_enabled   = "true"
  additional_cidr_blocks = [
    "10.10.40.0/22",
  ]
}

module "vapi-response-cache" {
  # checkov:skip=CKV_AWS_30:ElastiCache encryption in transit requires client library update.
  # checkov:skip=CKV_AWS_31:ElastiCache encryption in transit requires client library update.
  source = "git@github.com:theorchard/terraform-elasticache.git//?ref=3.1.1"

  providers = {
    aws.dns = aws.networking
  }

  environment                      = var.environment
  service_name                     = "${var.service_name}-response-cache"
  cache_parameter_group_name       = "default.redis7"
  redis_engine_version             = "7.1"
  application_family               = var.application_family
  cache_engine                     = "redis"
  cache_node_type                  = "cache.t4g.medium"
  cache_subnet_group_name          = "${var.environment}-elasticache-subnet-group"
  cache_transit_encryption_enabled = false
  route53_zone_id                  = data.aws_route53_zone.zone.zone_id
  vpc_id                           = module.vpc_info.vpc_id
  additional_cidr_blocks_enabled   = "true"
  additional_cidr_blocks = [
    "10.10.40.0/22",
  ]
}

module "vapi_doctrine_cache_cluster" {
  # checkov:skip=CKV_AWS_30:ElastiCache encryption in transit requires client library update.
  # checkov:skip=CKV_AWS_31:ElastiCache encryption in transit requires client library update.
  source = "git@github.com:theorchard/terraform-elasticache.git//?ref=3.1.1"

  providers = {
    aws.dns = aws.networking
  }

  environment                      = var.environment
  service_name                     = "${var.service_name}-doctrine"
  application_family               = var.application_family
  cache_engine                     = "memcached"
  cache_subnet_group_name          = "${var.environment}-elasticache-subnet-group"
  memcached_engine_version         = "1.5.16"
  cache_parameter_group_name       = "default.memcached1.5"
  cache_node_count                 = 1
  cache_node_type                  = "cache.t4g.small"
  cache_transit_encryption_enabled = false
  route53_zone_id                  = data.aws_route53_zone.zone.zone_id
  vpc_id                           = module.vpc_info.vpc_id
  additional_cidr_blocks_enabled   = "true"
  additional_cidr_blocks = [
    "10.10.40.0/22",
  ]
}

# Create KMS key and policies for certain encrypted configuration
resource "aws_kms_key" "vapi_kms_key" {
  description             = "${var.environment}-${var.service_name}"
  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" "vapi_kms_alias" {
  name          = "alias/${var.environment}-${var.service_name}"
  target_key_id = aws_kms_key.vapi_kms_key.key_id
}

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

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

# Create KMS policy
resource "aws_iam_policy" "vapi_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
  }
}

# Data resource for read-only policy to the S3 bucket
data "aws_iam_policy_document" "s3_configs_read_only_policy" {
  statement {
    actions = [
      "s3:GetBucketLocation",
      "s3:GetObject",
      "s3:ListBucket",
    ]

    resources = [
      "arn:aws:s3:::${var.config_s3_bucket}/${var.service_name}/${var.environment}/*",
      "arn:aws:s3:::${var.config_s3_bucket}/orchard-sqlrelay/${var.environment}/*",
    ]
  }

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

    resources = [
      "arn:aws:s3:::${var.config_s3_bucket}",
    ]
  }

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

    resources = [
      "*",
    ]
  }
}

# Creates policy for read-only access to the S3 bucket
resource "aws_iam_policy" "s3_configs_read_only_policy" {
  name   = "S3-${var.environment}-${var.service_name}-RO"
  policy = data.aws_iam_policy_document.s3_configs_read_only_policy.json

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

data "aws_acm_certificate" "theorchard_dot_io" {
  domain   = "*.theorchard.io"
  statuses = ["ISSUED"]
}

resource "aws_lb_listener_certificate" "vapi_theorchard_io_cert" {
  listener_arn    = module.vapi_fargate_environment.fargate_load_balancer_https_listener_arn
  certificate_arn = data.aws_acm_certificate.theorchard_dot_io.arn
}

module "service_info" {
  for_each     = toset(local.downstream_services)
  source       = "git@github.com:theorchard/terraform-service-info.git//?ref=1.0.0"
  service_name = each.value
  environment  = var.environment
}

data "aws_elasticache_replication_group" "split_synchronizer_redis_cache" {
  replication_group_id = "${var.environment}-split-synchronizer"
}

data "aws_secretsmanager_secret" "splitio_api_key" {
  name = "${var.environment}/split/API_KEY"
}

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

  providers = {
    aws.dns = aws.networking
  }

  environment                     = var.environment
  service_name                    = var.service_name
  aws_region                      = var.aws_region
  application_family              = var.application_family
  use_custom_task_definition_file = true
  task_definition_file_location = templatefile("vapi.json", {
    sentry_dsn          = module.sentry_vapi.sentry_key_dsn_public_output,
    is_defender_enabled = false,
    splitio_redis_host  = data.aws_elasticache_replication_group.split_synchronizer_redis_cache.primary_endpoint_address,
    splitio_redis_port  = data.aws_elasticache_replication_group.split_synchronizer_redis_cache.port,
    splitio_api_key_arn = data.aws_secretsmanager_secret.splitio_api_key.arn,
  })
  service_platform_version                 = "1.4.0"
  deployment_minimum_healthy_percent       = "100"
  desired_task_count                       = 2
  minimum_capacity                         = 2
  maximum_capacity                         = 6
  task_cpu                                 = 4096
  task_memory                              = 8192
  container_port                           = 80
  health_check_grace_period_seconds        = 120
  container_start_period_seconds           = 120
  health_check_path                        = "/healthchk.php"
  load_balancer_access_logs_s3_bucket_name = "orch-elb-logs"
  vpc_id                                   = module.vpc_info.vpc_id
  custom_waf_arn                           = module.custom_waf.waf_blocking_arn_output
  stopped_task_monitoring_enabled          = true
  # ACM certificate id for theorchard.com
  https_listener_certificate_id = split("/", data.aws_acm_certificate.theorchard_com.arn)[1]
  iam_managed_policy_attachments = [
    aws_iam_policy.vapi_kms_policy.arn,
    aws_iam_policy.s3_configs_read_only_policy.arn,
  ]

  prod_https_listener_allow_cidr_blocks = [
    "10.10.40.0/22",
  ]

  fargate_service_subnets = module.vpc_info.default_private_subnet_ids

  load_balancer_subnets = module.vpc_info.default_private_subnet_ids

  https_listener_allow_security_group_ids = flatten(
    [for service in module.service_info : service.security_groups]
  )

  # Environment_variables are managed in the task definition json file,
  # but it's better to keep them here as well for updating the custom task definition file.
  environment_variables = [
    {
      Environment = var.environment
    },
    {
      APPLICATION_ENV = "production"
    },
    {
      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}"
    },
    {
      PHP_DISPLAY_ERRORS = "false"
    },
    {
      PHP_POST_MAX_SIZE = "8M"
    },
    {
      PHP_SESSION_COOKIE_SECURE = "1"
    },
    {
      PHP_SESSION_COOKIE_HTTPONLY = "1"
    },
    {
      PHP_UPLOAD_MAX_FILESIZE = "2M"
    },
    {
      S3_CONFIG_LOCATION = "${var.config_s3_bucket}/${var.service_name}/${var.environment}"
    },
    {
      PHP_MEMORY_LIMIT = "4096M"
    },
    {
      PHP_MAX_EXECUTION_TIME = "60"
    },
    {
      SPLITIO_REDIS_HOST = data.aws_elasticache_replication_group.split_synchronizer_redis_cache.primary_endpoint_address
    },
    {
      SPLITIO_REDIS_PORT = data.aws_elasticache_replication_group.split_synchronizer_redis_cache.port
    },
  ]

  secrets = [
    {
      SPLITIO_API_KEY = "${var.environment}/split/API_KEY"
    },
  ]
}

module "custom_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 = [
    "GenericLFI_BODY",
    "NoUserAgent_HEADER",
    "SizeRestrictions_BODY",
  ]
}

resource "aws_iam_user_policy_attachment" "user_policy_attachment" {
  user       = data.aws_iam_user.user.user_name
  policy_arn = data.aws_iam_policy.ows_machine_to_machine_policy.arn
}

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

  environment                       = var.environment
  application_family                = var.application_family
  environment_type                  = "fargate"
  service_name                      = var.service_name
  notification_endpoints            = "@slack-devops"
  escalation_notification_endpoints = "@slack-devops @oncall-devops"
  alert_notification_endpoints      = "@oncall-devops"
  no_data_notification_endpoints    = "@oncall-devops"

  service_4xx_monitor_enabled  = true
  critical_number_4xx          = 100
  critical_recovery_number_4xx = 90
  warning_number_4xx           = 80
  warning_recovery_number_4xx  = 75

  critical_number_5xx          = 50
  critical_recovery_number_5xx = 45
  warning_number_5xx           = 30
  warning_recovery_number_5xx  = 25
}

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

  environment        = var.environment
  service_name       = "${var.service_name}-data-cache"
  application_family = var.application_family

  notification_endpoints            = "@slack-devops"
  escalation_notification_endpoints = "@slack-devops"
  #escalation_notification_endpoints = "@slack-devops @oncall-devops"
}

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

  environment        = var.environment
  service_name       = "${var.service_name}-response-cache"
  application_family = var.application_family

  notification_endpoints                           = "@slack-devops"
  escalation_notification_endpoints                = "@slack-devops"
  database_memory_usage_percentage_critical_number = 90
  database_memory_usage_percentage_warning_number  = 80
  #escalation_notification_endpoints = "@slack-devops @oncall-devops"
}

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

  environment        = var.environment
  service_name       = "${var.service_name}-doctrine-cache"
  application_family = var.application_family

  notification_endpoints            = "@slack-devops"
  escalation_notification_endpoints = "@slack-devops"
  #escalation_notification_endpoints = "@slack-devops @oncall-devops"
}

# Sentry
module "sentry_vapi" {
  source = "git@github.com:theorchard/terraform-sentry.git//?ref=4.1.2"

  environment        = var.environment
  application_family = var.application_family
  service_name       = var.service_name
  teams              = [var.environment]
  platform           = "php"
}

module "m2m_secrets" {
  source = "git@github.com:theorchard/terraform-secrets-manager.git//modules/auth0m2m?ref=1.6.1"

  environment        = var.environment
  service_name       = var.service_name
  application_family = var.application_family
}
