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

provider "cloudflare" {}

terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "prod/ows-metadata/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_acm_certificate" "theorchard_dot_io" {
  domain   = "*.theorchard.io"
  statuses = ["ISSUED"]
}

resource "aws_lb_listener_certificate" "ows_metadata_theorchard_io_cert" {
  listener_arn    = module.ows_metadata_fargate_environment.fargate_load_balancer_https_listener_arn
  certificate_arn = data.aws_acm_certificate.theorchard_dot_io.arn
}


data "cloudflare_zone" "cloudflare_cloudflare_zone" {
  name = var.cloudflare_domain_name
}

# Create KMS key and policies for certain encrypted configuration
resource "aws_kms_key" "ows_metadata_kms_key" {
  description             = "${var.environment}-${var.service_name}"
  enable_key_rotation     = true
  deletion_window_in_days = 30
}

resource "aws_kms_alias" "ows_metadata_kms_alias" {
  name          = "alias/${var.environment}-${var.service_name}"
  target_key_id = aws_kms_key.ows_metadata_kms_key.key_id
}

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

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

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

# 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}/*",
    ]
  }

  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
}

# Memcached session and doctrine cache
module "ows_metadata_cache_cluster" {
  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}-session-doctrine-cache"
  cache_engine               = "memcached"
  memcached_engine_version   = "1.6.6"
  cache_subnet_group_name    = "${var.environment}-elasticache-subnet-group"
  cache_parameter_group_name = "default.memcached1.6"
  cache_node_count           = 1
  cache_node_type            = "cache.t4g.medium"
  application_family         = var.application_family
  route53_zone_id            = data.aws_route53_zone.route53_zone.zone_id
  vpc_id                     = module.vpc_info.vpc_id
}

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

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

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

module "ows_metadata_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"
  deployment_minimum_healthy_percent = "100"
  desired_task_count                 = 10
  minimum_capacity                   = 10
  maximum_capacity                   = 14
  task_cpu                           = 4 * 1024
  task_memory                        = 14 * 1024
  container_port                     = 80
  health_check_grace_period_seconds  = 120
  container_start_period_seconds     = 120
  health_check_path                  = "/healthchk.php"
  route53_zone_id                    = data.aws_route53_zone.route53_zone.zone_id

  vpc_id                     = module.vpc_info.vpc_id
  load_balancer_idle_timeout = "300"
  datadog_task_memory        = 512

  # CPU scaling settings (default).
  autoscaling_cpu_policy_enabled = true
  scaling_cpu_target_value       = 40

  # Memory scaling settings.
  autoscaling_memory_policy_enabled = true
  scaling_memory_target_value       = 60

  # 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.ows_metadata_kms_policy.arn,
    aws_iam_policy.s3_configs_read_only_policy.arn,
  ]

  # Overriding this since users (Operations primarily) need to reach the service
  prod_https_listener_allow_cidr_blocks = [
    "192.168.31.0/24",
    "192.168.32.0/24",
    "192.168.33.0/24",
    "192.168.40.0/22",
    "10.30.0.0/22",
    "10.40.0.0/22",
    "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

  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_MAX_EXECUTION_TIME = "300"
    },
    {
      PHP_MEMORY_LIMIT = "512M"
    },
    {
      PHP_SESSION_COOKIE_SECURE = "1"
    },
    {
      PHP_SESSION_COOKIE_HTTPONLY = "1"
    },
    {
      PHP_UPLOAD_MAX_FILESIZE = "2M"
    },
    {
      SENTRY_DSN = module.sentry_ows_metadata.sentry_key_dsn_public_output
    },
    {
      ART_DB_HOST = var.art_db_host
    },
    {
      ART_DB_USER = var.art_db_user
    },
    {
      DD_DB_HOST = var.dd_db_host
    },
    {
      DD_DB_USER = var.dd_db_user
    },
    {
      REDIS_HOST = data.aws_elasticache_replication_group.ows_metadata_redis_cache.primary_endpoint_address
    },
    {
      REDIS_PORT = data.aws_elasticache_replication_group.ows_metadata_redis_cache.port
    },
    {
      AWS_REGION = var.aws_region
    },
  ]
  secrets = [
    {
      AR_DB_PASSWORD = "${var.environment}/${var.service_name}/AR_DB_PASSWORD"
    },
    {
      DD_DB_PASSWORD = "${var.environment}/${var.service_name}/DD_DB_PASSWORD"
    },
    {
      AWS_KEY = "${var.environment}/${var.service_name}/AWS_KEY"
    },
    {
      AWS_SECRET = "${var.environment}/${var.service_name}/AWS_SECRET"
    },
    {
      SPLIT_API_KEY = "${var.environment}/split/API_KEY"
    },
  ]
}

module "ows_metadata_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
  notification_endpoints            = "@slack-distro-prod-alerts"
  escalation_notification_endpoints = "@slack-distro-prod-alerts"
  service_cpu_monitor_enabled       = false
  critical_number_5xx               = 750
  critical_recovery_number_5xx      = 700
  warning_number_5xx                = 600
  warning_recovery_number_5xx       = 500
  critical_number_4xx               = 100
  critical_recovery_number_4xx      = 90
  warning_number_4xx                = 80
  warning_recovery_number_4xx       = 75

  healthy_tasks_notification_overrides = {
    endpoints            = var.healthy_tasks_notification_endpoints
    escalation_endpoints = var.healthy_tasks_notification_endpoints
  }
}

module "secrets_ows_metadata" {
  source   = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.5.1"
  for_each = toset(var.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
}

resource "cloudflare_record" "owsmetadata_cloudflare_record" {
  zone_id = data.cloudflare_zone.cloudflare_cloudflare_zone.id
  name    = "webservices"
  ttl     = 60
  content = module.ows_metadata_fargate_environment.prod_fargate_service_route53_record_fqdn_output
  type    = "CNAME"
  proxied = false
}

# Auth0 M2M credentials for service-to-service authentication
# Rotates automatically via Lambda function
module "ows_metadata_m2m_secret" {
  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
}
