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

data "aws_caller_identity" "current" {}

data "aws_s3_bucket" "logging_bucket" {
  bucket = "aws-waf-logs-prod-tf-orcd-bucket"
}

module "vpc_info" {
  source = "git@github.com:theorchard/terraform-vpc-info.git?ref=3.0.2"

  environment = var.environment
}

data "aws_acm_certificate" "qaorch_com" {
  domain      = "*.qaorch.com"
  statuses    = ["ISSUED"]
  most_recent = true
}

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

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

data "aws_iam_policy_document" "sftp_private_connection_secrets" {
  statement {
    effect = "Allow"
    actions = [
      "secretsmanager:GetResourcePolicy",
      "secretsmanager:GetSecretValue",
      "secretsmanager:DescribeSecret",
      "secretsmanager:PutSecretValue",
      "secretsmanager:CreateSecret",
      "secretsmanager:DeleteSecret",
      "secretsmanager:ListSecretVersionIds",
      "secretsmanager:UpdateSecret",
      "secretsmanager:TagResource"
    ]
    resources = [
      "arn:aws:secretsmanager:${var.aws_region}:${data.aws_caller_identity.current.account_id}:secret:${var.environment}/direct_delivery/connection_info/",
      "arn:aws:secretsmanager:${var.aws_region}:${data.aws_caller_identity.current.account_id}:secret:${var.environment}/direct_delivery/connection_info/*"
    ]
  }

  statement {
    effect    = "Allow"
    actions   = ["secretsmanager:GetRandomPassword"]
    resources = ["*"]
  }
}

resource "aws_iam_policy" "sftp_private_connection_secrets_policy" {
  name   = "SecretsManager-${var.environment}-direct_delivery-connection_info-read-write-policy"
  policy = data.aws_iam_policy_document.sftp_private_connection_secrets.json
}

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

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

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

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
}

resource "aws_iam_user_policy_attachment" "iam-user-policy-attachment" {
  user       = data.aws_iam_user.user.user_name
  policy_arn = aws_iam_policy.sftp_private_connection_secrets_policy.arn
}

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

data "aws_s3_bucket" "asset_bucket" {
  bucket = "${var.environment}-${var.asset_bucket_name}"
}

data "aws_s3_bucket" "video_asset_bucket" {
  bucket = "${var.environment}-${var.video_asset_bucket_name}"
}

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

data "aws_iam_policy_document" "s3_asset_bucket_policy" {
  statement {
    actions = [
      "s3:ListBucket",
    ]

    resources = [
      data.aws_s3_bucket.asset_bucket.arn,
      data.aws_s3_bucket.video_asset_bucket.arn,
    ]
  }

  statement {
    actions = [
      "s3:GetObject"
    ]

    resources = [
      "${data.aws_s3_bucket.asset_bucket.arn}/*",
      "${data.aws_s3_bucket.video_asset_bucket.arn}/*",
    ]
  }
}

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

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

# Create efs file system for shared mounts
module "efs_volume" {
  source = "git@github.com:theorchard/terraform-efs.git//?ref=4.1.0"

  providers = {
    aws.dns = aws.networking
  }

  environment              = var.environment
  service_name             = var.service_name
  application_family       = var.application_family
  vpc_id                   = module.vpc_info.vpc_id
  subnet_ids               = module.vpc_info.default_private_subnet_ids
  owner_gid                = "33"
  owner_uid                = "33"
  access_point_permissions = "700"
}

# 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.oa_fargate_environment.fargate_security_group_id
  type                     = "ingress"
}

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

  rule {
    name     = "query-string-length-rule"
    priority = 1

    action {
      block {}
    }

    statement {

      size_constraint_statement {

        comparison_operator = "GT"

        field_to_match {
          query_string {}
        }

        size = 20480

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

    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name                = "query-string-length-rule"
      sampled_requests_enabled   = true
    }
  }

  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name                = "query-string-length-rule"
    sampled_requests_enabled   = true
  }

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

module "custom_waf" {
  source            = "git@github.com:theorchard/terraform-aws-waf.git//?ref=1.5.0"
  environment       = var.environment
  service_name      = var.service_name
  aws_region        = var.aws_region
  count_waf_enabled = false
  block_waf_enabled = true

  logging_config_default_destination = data.aws_s3_bucket.logging_bucket.arn

  # See https://theorchard.atlassian.net/browse/DEVEX-392 for exclusion explanations
  excluded_rules = [
    "CrossSiteScripting_BODY",
    "NoUserAgent_HEADER",
    "SizeRestrictions_BODY",
    "SizeRestrictions_QUERYSTRING",
  ]
  custom_rules = [
    {
      name                       = "custom-query-string-length-group"
      rule_group_arn             = aws_wafv2_rule_group.oa_rule_group.arn
      priority                   = 2
      cloudwatch_metrics_enabled = true
      metric_name                = "waf-block-acl"
      sampled_requests_enabled   = true
    },
  ]
}

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

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

  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                       = 2
  minimum_capacity                         = 2
  maximum_capacity                         = 4
  task_cpu                                 = 2048
  task_memory                              = 4096
  container_port                           = 8080
  health_check_grace_period_seconds        = 300
  container_start_period_seconds           = 300
  health_check_path                        = "/healthchk.php"
  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.custom_waf.waf_blocking_arn_output
  # ACM certificate id for qaorch.com
  https_listener_certificate_id = split("/", data.aws_acm_certificate.qaorch_com.arn)[1]
  iam_managed_policy_attachments = [
    aws_iam_policy.oa_kms_policy.arn,
    aws_iam_policy.s3_configs_read_only_policy.arn,
    aws_iam_policy.s3_asset_bucket_policy.arn,
    module.efs_volume.efs_iam_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
    }
  ]

  https_listener_allow_prefix_list_names = [
    "sme-infosec-vm-network",
  ]

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      APPLICATION_ENV = "testing"
    },
    {
      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_SESSION_COOKIE_SECURE = "1"
    },
    {
      PHP_SESSION_COOKIE_HTTPONLY = "1"
    },
    {
      PHP_SESSION_SAVE_HANDLER = "memcached"
    },
    {
      PHP_SESSION_SAVE_PATH = "${var.environment}-oa-workstation-session-cache-memcached.theorchard.io:11211"
    },
    {
      PHP_SESSION_GC_MAXLIFETIME = "14400"
    },
    {
      S3_CONFIG_LOCATION = "${var.config_s3_bucket}/${var.service_name}/${var.environment}"
    },
    {
      EFS_VOLUME_CONTAINER_PATH = var.efs_volume_container_path
    },
    {
      PHP_MEMORY_LIMIT = "1024M"
    },
    {
      API_BASE_URL = "https://qa-orchard.auth0.com"
    },
    {
      OA_DOMAIN = "qalogin.theorchard.com"
    },
    {
      OA_CALLBACK_URL = "https://oa.qaorch.com/login_v2.php"
    },
    {
      AUDIENCE = "https://workstation.qaorch.com/api"
    },
    {
      CONNECTION = "art-relations"
    },
    {
      OA_COOKIE_EXPIRY = "604800"
    },
    {
      LC_ALL = "en_US.UTF-8"
    },
    {
      LANG = "en_US.UTF-8"
    },
    {
      LANGUAGE = "en_US.UTF-8"
    },
    {
      SPLITIO_REDIS_HOST = data.aws_elasticache_replication_group.oa_split_synchronizer_redis_cache.primary_endpoint_address
    },
    {
      SPLITIO_REDIS_PORT = data.aws_elasticache_replication_group.oa_split_synchronizer_redis_cache.port
    },
    {
      YOUTUBE_OAUTH_REDIRECT_URL = "http://klasalvia.marketing.devorch.com/YoutubeAuthManually.php"
    },
    {
      YOUTUBE_OAUTH_SCOPES = "https://www.googleapis.com/auth/youtube,https://www.googleapis.com/auth/youtube.readonly,https://www.googleapis.com/auth/youtube.upload,https://www.googleapis.com/auth/youtubepartner"
    },
    {
      YOUTUBE_OAUTH_APPROVAL_PROMPT = "auto"
    },
    {
      YOUTUBE_OAUTH_ACCESS_TYPE = "offline"
    }
  ]

  secrets = [
    {
      OA_CLIENT_ID = "${var.environment}/${var.service_name}/OA_CLIENT_ID"
    },
    {
      OA_CLIENT_SECRET = "${var.environment}/${var.service_name}/OA_CLIENT_SECRET"
    },
    {
      OA_COOKIE_SECRET = "${var.environment}/${var.service_name}/OA_COOKIE_SECRET"
    },
    {
      MACHINE_CLIENT_ID = "${var.environment}/${var.service_name}/MACHINE_CLIENT_ID"
    },
    {
      MACHINE_CLIENT_SECRET = "${var.environment}/${var.service_name}/MACHINE_CLIENT_SECRET"
    },
    {
      SENTRY_DSN = "${var.environment}/${var.service_name}/SENTRY_DSN"
    },
    {
      SPLITIO_API_KEY = "${var.environment}/split/API_KEY"
    },
    {
      YOUTUBE_OAUTH_CLIENT_ID = "${var.environment}/${var.service_name}/YOUTUBE_OAUTH_CLIENT_ID"
    },
    {
      YOUTUBE_OAUTH_CLIENT_SECRET = "${var.environment}/${var.service_name}/YOUTUBE_OAUTH_CLIENT_SECRET"
    },
    {
      YOUTUBE_OAUTH_DEVELOPER_KEY = "${var.environment}/${var.service_name}/YOUTUBE_OAUTH_DEVELOPER_KEY"
    },
  ]
}

module "sentry_project" {
  source             = "git@github.com:theorchard/terraform-sentry.git//?ref=4.1.2"
  service_name       = var.service_name
  environment        = var.environment
  teams              = [var.environment]
  application_family = var.application_family
  platform           = "php"
}

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 "oa_fargate_service_dashboard" {
  source = "git@github.com:theorchard/terraform-datadog.git//modules/service?ref=6.10.7"

  environment                       = var.environment
  environment_type                  = "fargate"
  service_name                      = var.service_name
  application_family                = var.application_family
  notification_endpoints            = "@slack-the-build-is-broken"
  escalation_notification_endpoints = ""
  service_4xx_monitor_enabled       = false
}
