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     = "uat/ows-grass/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_io" {
  domain   = "*.theorchard.io"
  statuses = ["ISSUED"]
}

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

module "ows_service_owsrequest" {
  source = "git@github.com:theorchard/terraform-owsrequest.git//?ref=1.1.0"

  environment_name = var.environment
  service_name     = var.service_name
}

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

  providers = {
    aws.dns = aws.networking
  }

  environment                   = var.environment
  service_name                  = var.service_name
  application_family            = var.application_family
  aws_region                    = var.aws_region
  commit_sha                    = "latest"
  container_port                = "8080"
  task_type                     = "web_service"
  desired_task_count            = 2
  task_cpu                      = 1024
  task_memory                   = 2048
  maximum_capacity              = 4
  minimum_capacity              = 2
  route53_zone_id               = data.aws_route53_zone.route53_zone.zone_id
  https_listener_ssl_policy     = "ELBSecurityPolicy-TLS13-1-2-2021-06"
  vpc_id                        = module.vpc_info.vpc_id
  https_listener_certificate_id = split("/", data.aws_acm_certificate.theorchard_io.arn)[1]
  custom_waf_arn                = module.ows_grass_waf.waf_blocking_arn_output

  https_listener_allow_prefix_list_names = [
    "uat-accounting-private-subnet-prefix-list",
    "vpn-ny-users",
    "vpn-sme-internal-primary"
  ]

  iam_managed_policy_attachments = [
    "arn:aws:iam::aws:policy/AmazonElastiCacheFullAccess",
    "arn:aws:iam::aws:policy/CloudWatchFullAccess",
    module.ows_service_owsrequest.policy_arn_output,
  ]

  fargate_service_subnets = module.vpc_info.default_private_subnet_ids

  load_balancer_subnets = module.vpc_info.default_private_subnet_ids

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      LOGGER_HANDLER_ASYNC = var.LOGGER_HANDLER_ASYNC
    },
    {
      REDIS_HOST = module.ows_grass_elasticache.redis_primary_endpoint_address
    },
    {
      REDIS_PORT = var.REDIS_PORT
    },
    {
      SESSION_DURATION = var.SESSION_DURATION
    },
    {
      JWT_SERVICE_NAME = var.JWT_SERVICE_NAME
    },
    {
      JWT_SECRET_NAME = var.JWT_SECRET_NAME
    },
    {
      JWT_REFRESH_INTERVAL = var.JWT_REFRESH_INTERVAL
    },
    {
      SENTRY_DSN = module.sentry_ows_grass.sentry_key_dsn_public_output
    },
  ]

  secrets = [
    {
      AUTH0_API_AUDIENCE = "${var.environment}/ows-grass/AUTH0_API_AUDIENCE"
    },
    {
      AUTH0_DOMAIN = "${var.environment}/ows-grass/AUTH0_DOMAIN"
    },
    {
      DB_URL = "${var.environment}/ows-grass/DB_URL"
    },
  ]
}

module "secrets" {
  source   = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.5.1"
  for_each = toset(var.secrets_manager_secret_names)

  environment                    = var.environment
  service_name                   = var.service_name
  secret_name                    = each.value
  application_family             = var.application_family
  secret_recovery_window_in_days = 7
}

module "fargate_service_dashboard" {
  source                            = "git@github.com:theorchard/terraform-datadog.git//modules/service?ref=6.13.6"
  environment                       = var.environment
  environment_type                  = "fargate"
  service_name                      = var.service_name
  service_cpu_monitor_silenced      = true
  service_4xx_monitor_enabled       = false
  service_5xx_monitor_silenced      = false
  critical_number_5xx               = 50
  critical_recovery_number_5xx      = 25
  warning_number_5xx                = 20
  warning_recovery_number_5xx       = 10
  ok_number_5xx                     = 5
  application_family                = var.application_family
  notification_endpoints            = var.notification_endpoints
  escalation_notification_endpoints = var.escalation_notification_endpoints
  teams                             = [var.application_family]
}

resource "aws_wafv2_rule_group" "grass_post_body_size" {
  name        = "${var.environment}-${var.service_name}-custom-rule-group"
  description = "${var.environment}-${var.service_name} custom rule group"
  scope       = "REGIONAL"
  capacity    = 500

  rule {
    name     = "post-body-size-rule"
    priority = 1

    action {
      block {}
    }

    statement {

      size_constraint_statement {

        comparison_operator = "GT"

        field_to_match {
          body {}
        }

        size = 131072

        text_transformation {
          priority = 1
          type     = "COMPRESS_WHITE_SPACE"
        }
      }
    }

    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name                = "post-body-size-rule"
      sampled_requests_enabled   = true
    }
  }

  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name                = "post-body-size-rule-group"
    sampled_requests_enabled   = true
  }

  tags = {
    Name         = "${var.environment}-${var.service_name}-custom-rule-group"
    terraformed  = "true"
    environment  = var.environment
    service_name = var.service_name
  }
}

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

  custom_rules = [
    {
      name                       = "${var.environment}-${var.service_name}-waf-custom-rules-group"
      rule_group_arn             = aws_wafv2_rule_group.grass_post_body_size.arn
      priority                   = 20
      cloudwatch_metrics_enabled = true
      metric_name                = "waf-block-acl"
      sampled_requests_enabled   = true
    },
  ]
}

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

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

module "ows_grass_elasticache" {
  # checkov:skip=CKV_AWS_30:Ensure all data stored in the ElastiCache Replication Group is securely encrypted at transit
  # checkov:skip=CKV_AWS_31:Ensure all data stored in the ElastiCache Replication Group is securely encrypted at transit and has auth token
  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
  application_family               = var.application_family
  cache_engine                     = "redis"
  redis_engine_version             = "5.0.6"
  cache_subnet_group_name          = "${var.environment}-elasticache-subnet-group"
  cache_transit_encryption_enabled = false
  redis_snapshot_window            = "08:30-09:30"
  cache_maintenance_window         = "wed:06:00-wed:07:00"
  cache_node_type                  = "cache.t4g.micro"
  cache_parameter_group_name       = "default.redis5.0"
  route53_zone_id                  = data.aws_route53_zone.route53_zone.zone_id
  vpc_id                           = module.vpc_info.vpc_id
}

