module "default_tags" {
  source             = "git@github.com:theorchard/terraform-default-tags.git//?ref=1.0.0"
  environment        = var.environment
  application_family = var.application_family
  service_name       = var.service_name
}

provider "aws" {
  region = var.aws_region

  default_tags {
    tags = module.default_tags.tags
  }
}

# Terraform backends cannot contain interpolations
provider "aws" {
  alias  = "aws_us_west_2"
  region = "us-west-2"

  default_tags {
    tags = module.default_tags.tags
  }
}

# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "prod/workstation/awal/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

data "aws_caller_identity" "current" {}

# TODO: add cloudflare support
# data "cloudflare_ip_ranges" "cloudflare" {}

# data "cloudflare_zone" "cloudflare_domain" {
#   name = var.domain_name
# }

data "aws_ec2_managed_prefix_list" "cloudfront" {
  name = "com.amazonaws.global.cloudfront.origin-facing"
}

data "aws_route53_zone" "prodawal_zone" {
  name         = var.domain_name
  private_zone = false
}

data "aws_acm_certificate" "awal_certificate" {
  domain   = "*.${var.real_domain_name}"
  statuses = ["ISSUED"]
}

data "aws_route53_zone" "theorchard_io_zone" {
  name         = "theorchard.io."
  private_zone = false
}

data "aws_cloudfront_origin_request_policy" "policy" {
  name = "Managed-AllViewer"
}

data "aws_cloudfront_cache_policy" "spa_policy" {
  name = "Managed-CachingOptimized"
}

data "aws_cloudfront_cache_policy" "dynamic_policy" {
  name = "Managed-CachingDisabled"
}

data "aws_s3_bucket" "bucket_primary" {
  bucket = "${var.environment}-orcd-cdn"
}

data "aws_s3_bucket" "bucket_failover" {
  bucket   = "${var.environment}-orcd-cdn-us-west01"
  provider = aws.aws_us_west_2
}

# Requires corresponding change to S3 bucket policies in orcd-cdn parent folder
resource "aws_cloudfront_origin_access_identity" "origin_access_identity_primary" {
  comment = "${var.environment}-${var.brand}-${var.service_name}-primary-origin-access-identity"
}

resource "aws_cloudfront_origin_access_identity" "origin_access_identity_failover" {
  comment = "${var.environment}-${var.brand}-${var.service_name}-failover-origin-access-identity"
}

resource "aws_cloudfront_function" "viewer_request" {
  name    = "${var.environment}-${var.brand}-${var.service_name}-viewer-request"
  runtime = "cloudfront-js-1.0"
  comment = "${var.environment}-${var.brand}-${var.service_name}-viewer-request"
  publish = true
  code    = file("functions/viewer-request.js")
}

resource "aws_cloudfront_distribution" "distribution" {
  # checkov:skip=CKV2_AWS_32:Cloudfront Distribution strict security headers policy. Still WIP org-wide
  # checkov:skip=ORCD_AWS_3:Ensure CloudFront distribution has a response headers policy attached. Testing below
  # checkov:skip=CKV2_AWS_47:Ensure AWS CloudFront attached WAFv2 WebACL is configured with AMR for Log4j Vulnerability
  # checkov:skip=CKV_AWS_374:Ensure AWS CloudFront web distribution has geo restriction enabled
  aliases             = [
    "${var.service_name}.${var.domain_name}",
    "${var.service_name}.${var.real_domain_name}"
  ]
  comment             = "${var.environment}-${var.brand}-${var.service_name}"
  enabled             = true
  is_ipv6_enabled     = true
  http_version        = "http2"
  price_class         = "PriceClass_All"
  web_acl_id          = module.custom_cloudfront_waf.waf_blocking_arn_output
  default_root_object = "index-awal.html"

  custom_error_response {
    error_caching_min_ttl = 0
    error_code            = 404
  }

  origin_group {
    origin_id = "s3_origin_group"

    failover_criteria {
      status_codes = [403, 500, 502, 503]
    }

    member {
      origin_id = "${var.environment}-orcd-cdn"
    }

    member {
      origin_id = "${var.environment}-orcd-cdn-us-west01"
    }
  }

  origin {
    domain_name = data.aws_s3_bucket.bucket_primary.bucket_domain_name
    origin_id   = "${var.environment}-orcd-cdn"
    origin_path = "/frontend-${var.service_name}"

    s3_origin_config {
      origin_access_identity = aws_cloudfront_origin_access_identity.origin_access_identity_primary.cloudfront_access_identity_path
    }
  }

  origin {
    domain_name = data.aws_s3_bucket.bucket_failover.bucket_domain_name
    origin_id   = "${var.environment}-orcd-cdn-us-west01"
    origin_path = "/frontend-${var.service_name}"

    s3_origin_config {
      origin_access_identity = aws_cloudfront_origin_access_identity.origin_access_identity_failover.cloudfront_access_identity_path
    }
  }

  origin {
    domain_name = "workstation-lb.theorchard.com"
    origin_id   = "php_origin"

    custom_origin_config {
      http_port                = 4443 # dummy, https only
      https_port               = 443
      origin_protocol_policy   = "https-only"
      origin_ssl_protocols     = ["TLSv1.2"]
      origin_keepalive_timeout = 60
      origin_read_timeout      = 60
    }
  }

  origin {
    domain_name = "ows-grass.${data.aws_route53_zone.theorchard_io_zone.name}"
    origin_id   = "grass_origin"

    custom_origin_config {
      http_port                = 4443 # dummy, https only
      https_port               = 443
      origin_protocol_policy   = "https-only"
      origin_ssl_protocols     = ["TLSv1.2"]
      origin_keepalive_timeout = 60
      origin_read_timeout      = 60
    }
  }

  # Ordered cache behaviors for all patterns
  # By specifying a cache policy, we do not explicitly specify TTLs
  # SPA path patterns should use a CachingOptimized cache policy and not use origin request policies
  # Dynamic content (i.e. custom origins in our case) should forward everything to the origin
  dynamic "ordered_cache_behavior" {
    for_each = var.ordered_cache_behaviors

    content {
      path_pattern             = ordered_cache_behavior.value.path_pattern
      allowed_methods          = ordered_cache_behavior.value.allowed_methods
      cached_methods           = ["GET", "HEAD", "OPTIONS"]
      target_origin_id         = ordered_cache_behavior.value.target_origin_id
      cache_policy_id          = ordered_cache_behavior.value.target_origin_id == "s3_origin_group" ? data.aws_cloudfront_cache_policy.spa_policy.id : data.aws_cloudfront_cache_policy.dynamic_policy.id
      origin_request_policy_id = ordered_cache_behavior.value.target_origin_id == "s3_origin_group" ? null : data.aws_cloudfront_origin_request_policy.policy.id
      compress                 = true
      viewer_protocol_policy   = "redirect-to-https"

      dynamic "function_association" {
        for_each = ordered_cache_behavior.value.viewer_request_function_enabled ? [1] : []
        content {
          event_type   = "viewer-request"
          function_arn = aws_cloudfront_function.viewer_request.arn
        }
      }
    }
  }

  # All other unmatched requests will reach the SPA
  # By specifying a cache policy, we do not explicitly specify TTLs
  default_cache_behavior {
    allowed_methods        = ["GET", "HEAD", "OPTIONS"]
    cached_methods         = ["GET", "HEAD", "OPTIONS"]
    target_origin_id       = "s3_origin_group"
    cache_policy_id        = data.aws_cloudfront_cache_policy.spa_policy.id
    compress               = true
    viewer_protocol_policy = "redirect-to-https"

    function_association {
      event_type   = "viewer-request"
      function_arn = aws_cloudfront_function.viewer_request.arn
    }
  }

  restrictions {
    geo_restriction {
      restriction_type = "none"
    }
  }

  viewer_certificate {
    acm_certificate_arn      = data.aws_acm_certificate.awal_certificate.arn
    ssl_support_method       = "sni-only"
    minimum_protocol_version = var.cloudfront_minimum_protocol_version
  }

  logging_config {
    include_cookies = true
    bucket          = var.cloudfront_logging_bucket
    prefix          = "${var.environment}-${var.brand}-${var.service_name}"
  }

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

resource "aws_route53_record" "record" {
  zone_id = data.aws_route53_zone.prodawal_zone.zone_id
  name    = var.service_name
  type    = "A"

  alias {
    name                   = aws_cloudfront_distribution.distribution.domain_name
    zone_id                = aws_cloudfront_distribution.distribution.hosted_zone_id
    evaluate_target_health = false
  }
}
