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/oa/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_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 "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
}

data "aws_iam_policy_document" "assume_role_policy_document" {
  statement {
    effect  = "Allow"
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["backup.amazonaws.com"]
    }
  }
}

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

    resources = [
      "*",
    ]
  }
  statement {
    actions = [
      "s3:GetBucketLocation",
      "s3:ListBucket",
    ]

    resources = [
      "arn:aws:s3:::${var.environment}-orcd-raw-assets",
    ]
  }
  statement {
    actions = [
      "s3:Get*",
      "s3:List*",
      "s3:PutObject",
      "s3:PutObjectAcl",
    ]

    resources = [
      "arn:aws:s3:::${var.environment}-orcd-raw-assets/*",
    ]
  }
}

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
}

# attached the mezzanine asset access policy to iam user
resource "aws_iam_user_policy_attachment" "mezzanine_assets_user_policy_attachment" {
  user       = data.aws_iam_user.user.user_name
  policy_arn = aws_iam_policy.s3_asset_bucket_policy.arn
}

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

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

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
}

# S3 env-orcd-raw-assets policy
resource "aws_iam_policy" "oa_orcd_raw_assets_policy" {
  name   = "S3-oa-${var.environment}-orcd-raw-assets-readwrite-no-delete-policy"
  policy = data.aws_iam_policy_document.s3_read_write_policy.json
}

resource "aws_iam_user_policy_attachment" "oa_user_attachement" {
  user       = "${var.environment}-${var.service_name}-user"
  policy_arn = aws_iam_policy.oa_orcd_raw_assets_policy.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
}

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

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

# 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=2.0.1"
  environment       = var.environment
  service_name      = var.service_name
  aws_region        = var.aws_region
  count_waf_enabled = false
  block_waf_enabled = true
  # 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                   = 3
      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                       = 3
  minimum_capacity                         = 3
  maximum_capacity                         = 8
  task_cpu                                 = 4096
  task_memory                              = 8192
  container_port                           = 8080
  health_check_grace_period_seconds        = 300
  container_start_period_seconds           = 300
  health_check_path                        = "/healthchk.php"
  target_deregistration_delay              = 600
  load_balancer_idle_timeout               = "100"
  load_balancer_access_logs_s3_bucket_name = "orch-elb-logs"
  load_balancer_is_internal                = "false"
  vpc_id                                   = module.vpc_info.vpc_id
  fargate_service_subnets                  = module.vpc_info.default_private_subnet_ids
  load_balancer_subnets                    = module.vpc_info.default_public_subnet_ids
  custom_waf_arn                           = module.custom_waf.waf_blocking_arn_output
  # 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.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,
  ]
  # Cloudflare, AVL, and NY egress IPv4 address blocks
  prod_https_listener_allow_cidr_blocks = [
    "103.21.244.0/22",
    "103.22.200.0/22",
    "103.31.4.0/22",
    "104.16.0.0/12",
    "104.24.0.0/14",
    "108.162.192.0/18",
    "131.0.72.0/22",
    "141.101.64.0/18",
    "162.158.0.0/15",
    "172.64.0.0/13",
    "173.245.48.0/20",
    "188.114.96.0/20",
    "190.93.240.0/20",
    "197.234.240.0/22",
    "198.41.128.0/17",
    "207.237.185.2/32",
    "208.91.130.130/32",
  ]
  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
    }
  ]

  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_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"
    },
    {
      LC_ALL = "en_US.UTF-8"
    },
    {
      LANG = "en_US.UTF-8"
    },
    {
      LANGUAGE = "en_US.UTF-8"
    },
    {
      API_BASE_URL = "https://workstation.auth0.com"
    },
    {
      OA_DOMAIN = "login.distroauth.com"
    },
    {
      OA_CALLBACK_URL = "https://oa.theorchard.com/login_v2.php"
    },
    {
      AUDIENCE = "https://workstation.theorchard.com/api"
    },
    {
      CONNECTION = "art-relations"
    },
    {
      OA_COOKIE_EXPIRY = "604800"
    },
    {
      SENTRY_DSN = "https://45be02d6ec8847ddb46b572eace22652@o22178.ingest.us.sentry.io/67602"
    },
    {
      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"
    },
    {
      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 "oa_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-devops @oncall-devops"
  escalation_notification_endpoints = "@slack-devops @oncall-devops"
  service_4xx_monitor_enabled       = false
  service_cpu_time_window           = "last_10m"
  critical_number_5xx               = 100
  critical_recovery_number_5xx      = 90
  warning_number_5xx                = 80
  warning_recovery_number_5xx       = 75
}

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
}
