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
}

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/workstation/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.2.2"

  environment = var.environment
}

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

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

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

  tags = {
    environment        = var.environment
    service_name       = var.service_name
    application_family = var.application_family
    terraformed        = true
  }
}

resource "aws_iam_user_policy_attachment" "workstation_user_attachement" {
  user       = "${var.environment}-web-user"
  policy_arn = aws_iam_policy.workstation_orcd_raw_assets_policy.arn
}

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

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

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

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

  tags = {
    environment        = var.environment
    service_name       = var.service_name
    application_family = var.application_family
    terraformed        = true
  }
}

# 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

  tags = {
    environment        = var.environment
    service_name       = var.service_name
    application_family = var.application_family
    terraformed        = true
  }
}

# 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                = "48"
  owner_uid                = "48"
  access_point_permissions = "700"
}

# This rule will allow the fargate security group to access 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.workstation_fargate_environment.fargate_security_group_id
  type                     = "ingress"
}

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

module "custom_waf" {
  # checkov:skip=CKV2_AWS_31:count-only WAF is disabled but Checkov does not play nicely with dynamic statements
  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
  # See https://theorchard.atlassian.net/browse/DEVEX-393 for exclusion explanations
  excluded_rules = [
    "CrossSiteScripting_BODY",
    "EC2MetaDataSSRF_COOKIE",
    "EC2MetaDataSSRF_QUERYARGUMENTS",
    "NoUserAgent_HEADER",
    "SizeRestrictions_BODY",
    "SizeRestrictions_QUERYSTRING"
  ]
  logging_config_default_destination = data.aws_s3_bucket.logging_bucket_waf.arn
}

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_elasticache_replication_group" "split_synchronizer_redis_cache" {
  replication_group_id = "${var.environment}-split-synchronizer"
}

data "aws_secretsmanager_secret" "splitio_api_key" {
  name = "${var.environment}/split/API_KEY"
}

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

  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
  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.workstation_kms_policy.arn,
    aws_iam_policy.s3_configs_read_only_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
    }
  ]

  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 = "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"
    },
    {
      S3_CONFIG_LOCATION = "${var.config_s3_bucket}/${var.service_name}/${var.environment}"
    },
    {
      EFS_VOLUME_CONTAINER_PATH = var.efs_volume_container_path
    },
    {
      BULKUPLOAD_DOMAIN = var.bulkupload_domain_name
    },
    {
      API_BASE_URL = "https://qa-orchard.auth0.com"
    },
    {
      AUTH0_DOMAIN = "qalogin.theorchard.com"
    },
    {
      AUDIENCE = "https://workstation.qaorch.com/api"
    },
    {
      CONNECTION = "art-relations"
    },
    {
      WS_COOKIE_EXPIRY = "604800"
    },
    {
      SENTRY_DSN = var.sentry_dsn
    },
    {
      SPLITIO_REDIS_HOST = data.aws_elasticache_replication_group.split_synchronizer_redis_cache.primary_endpoint_address
    },
    {
      SPLITIO_REDIS_PORT = data.aws_elasticache_replication_group.split_synchronizer_redis_cache.port
    },
  ]

  secrets = [
    {
      WS_CLIENT_ID = "${var.environment}/${var.service_name}/WS_CLIENT_ID"
    },
    {
      WS_CLIENT_SECRET = "${var.environment}/${var.service_name}/WS_CLIENT_SECRET"
    },
    {
      WS_COOKIE_SECRET = "${var.environment}/${var.service_name}/WS_COOKIE_SECRET"
    },
    {
      AWAL_ORG_ID = "${var.environment}/${var.service_name}/AWAL_ORG_ID"
    },
    {
      SPLITIO_API_KEY = "${var.environment}/split/API_KEY"
    },
  ]
}

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

  application_family = "security-tools"
  environment        = var.environment
  service_name       = var.service_name
  secret_name        = each.value
}

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

data "aws_acm_certificate" "qaoverdrive_dot_com" {
  domain   = "*.qaoverdrive.com"
  statuses = ["ISSUED"]
}

resource "aws_lb_listener_certificate" "qaoverdrive_workstation_lb_listener_certificate" {
  listener_arn    = module.workstation_fargate_environment.fargate_load_balancer_https_listener_arn
  certificate_arn = data.aws_acm_certificate.qaoverdrive_dot_com.arn
}

data "aws_acm_certificate" "qaawal_dot_com" {
  domain   = "*.qaawal.com"
  statuses = ["ISSUED"]
}

resource "aws_lb_listener_certificate" "qaawal_workstation_lb_listener_certificate" {
  listener_arn    = module.workstation_fargate_environment.fargate_load_balancer_https_listener_arn
  certificate_arn = data.aws_acm_certificate.qaawal_dot_com.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
}

module "workstation_fargate_service_dashboard" {
  source = "git@github.com:theorchard/terraform-datadog.git//modules/service?ref=6.19.0"

  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 = "@slack-the-build-is-broken"
  service_4xx_monitor_enabled       = false
  service_5xx_monitor_enabled       = true
  critical_number_5xx               = 50
  critical_recovery_number_5xx      = 45
  warning_number_5xx                = 30
  warning_recovery_number_5xx       = 25
}

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