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 {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "prod/ows-transcoding/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"
}

data "aws_iam_policy" "pre_existing_policies" {
  for_each = toset(local.pre_existing_policy_names)
  name     = each.value
}

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

  environment_name   = var.environment
  service_name       = var.service_name
  policy_description = "Dynamo-${var.environment}-${var.service_name}-owsrequest"
}

data "aws_sqs_queue" "sqs_transcode_queue" {
  name = "${var.environment}-transcoding-jobs"
}

module "ows_transcoding_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
  commit_sha         = "latest"
  container_port     = "8080"
  task_type          = "web_service"
  desired_task_count = 2
  task_cpu           = 1024
  task_memory        = 2048
  maximum_capacity   = 16
  minimum_capacity   = 4
  route53_zone_id    = data.aws_route53_zone.route53_zone.id

  vpc_id                            = module.vpc_info.vpc_id
  https_listener_certificate_id     = split("/", data.aws_acm_certificate.theorchard_io.arn)[1]
  health_check_grace_period_seconds = 300
  container_start_period_seconds    = 300
  fargate_service_subnets           = module.vpc_info.default_private_subnet_ids
  load_balancer_subnets             = module.vpc_info.default_private_subnet_ids

  # Overriding here to add in the the ny internal and vpn private subnets ows-transcoding.
  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",
  ]

  iam_managed_policy_attachments = concat(
    [module.ows_transcoding_owsrequest.policy_arn_output],
    [for policy in data.aws_iam_policy.pre_existing_policies : policy.arn]
  )

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      DATADOG_ENV = "${var.environment}-${var.service_name}"
    },
    {
      DD_LOGS_INJECTION = "true"
    },
    {
      LOGGER_DSN = "https://${var.environment}-fluentd-applications.theorchard.io:8888/application"
    },
    {
      SQS_TRANSCODING_URL = data.aws_sqs_queue.sqs_transcode_queue.url
    },
    {
      TRANSCODED_ASSET_BASE_BUCKET_NAME = "${var.environment}-orcd-mezzanine-assets"
    },
    {
      SENTRY_DSN = module.sentry_ows_transcoding.sentry_key_dsn_public_output
    },
    {
      DB_USER = var.db_user
    },
    {
      DB_NAME = var.db_name
    },
    {
      DB_HOST = "${module.ows_transcoding_rds.rds_cluster_endpoint}:${module.ows_transcoding_rds.rds_cluster_port}"
    },
    {
      UWSGI_CHEAPER_RSS_LIMIT_SOFT = tostring(floor(pow(10, 9) * var.UWSGI_CHEAPER_RSS_LIMIT_SOFT_GB))
    },
  ]
}

module "sentry_ows_transcoding" {
  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]
}

# Setup datadog dashboards.
module "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-content-delivery-and-asset-mgmt-alerts"
  escalation_notification_endpoints = "@slack-content-delivery-and-asset-mgmt-alerts"
  critical_number_5xx               = "20"
  critical_recovery_number_5xx      = "15"
  ok_number_5xx                     = "2"
  warning_number_5xx                = "10"
  warning_recovery_number_5xx       = "5"
  service_cpu_time_window           = var.cpu_time_window

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

module "secrets_ows_transcoding" {
  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
}

module "ows_transcoding_rds" {
  source = "git@github.com:theorchard/terraform-rds.git//?ref=6.6.0"

  providers = {
    aws.dns = aws.networking
  }

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

  rds_master_username = "ows_transcoding_admin"
  rds_master_password = "s0mePass!changme"

  rds_cluster_instance_class                = "db.r6g.large"
  rds_cluster_instance_count                = "1"
  rds_db_cluster_parameter_group_name       = "aurora-mysql80sync"
  rds_cluster_instance_parameter_group_name = "default.aurora-mysql8.0"
  rds_engine                                = "aurora-mysql"
  rds_engine_version                        = "8.0.mysql_aurora.3.08.2"
  rds_db_subnet_group_name                  = "prod-orchard-private-subnet-group"
  rds_availability_zones                    = ["us-east-1a", "us-east-1c"]
  rds_performance_insights_enabled          = false
  enabled_cloudwatch_logs_exports           = ["audit", "error", "general"]
  custom_kms_key_enabled                    = true
  vpc_id                                    = module.vpc_info.vpc_id
  route53_zone_id                           = data.aws_route53_zone.route53_zone.id
}

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

  environment                       = var.environment
  application_family                = var.application_family
  service_name                      = var.service_name
  notification_endpoints            = "@slack-content-delivery-and-asset-mgmt-alerts"
  escalation_notification_endpoints = "@slack-monitoring @slack-content-delivery-and-asset-mgmt-alerts"
}
