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          = "devops"
}

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/neo4j-5/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_route53_zone" "networking_route53_zone" {
  provider = aws.networking

  name = "theorchard.io"
}

data "aws_route53_zone" "route53_zone" {
  zone_id = var.route53_zone_id
}

module "neo4j_5_debian_environment" {
  source = "git@github.com:theorchard/terraform-neo4j-cluster.git//debian?ref=1.1.0"

  providers = {
    aws.dns = aws.networking
  }

  environment                       = var.environment
  service_name                      = "${var.service_name}-debian"
  vpc_id                            = module.vpc_info.vpc_id
  vpc_private_subnet_ids            = module.vpc_info.default_private_subnet_ids
  data_volume_device_name           = "/dev/sdb"
  data_volume_device_type           = "io2"
  data_volume_iops                  = 6000
  data_volume_size                  = 6000
  data_volume_throughput            = null
  desired_capacity                  = 0
  min_size                          = 0
  max_size                          = 0
  ssh_keypair_name                  = "orchard_admin"
  route53_zone_id                   = var.route53_zone_id
  dbms_backup_s3_bucket             = "qa-orcdbucket"
  data_volume_delete_on_termination = true
  aws_instance_type                 = "r6idn.8xlarge"
  user_data                         = module.chef_bootstrap_neo4j_debian.user_data_output

  bolt_ingress_cidr_blocks = [
    "10.10.40.0/22",
    "10.30.0.0/22",
    "10.40.0.0/22",
    "192.168.31.0/24",
    "192.168.32.0/24",
    "192.168.33.0/24",
    "192.168.40.0/22",
  ]
}

module "chef_bootstrap_neo4j_debian" {
  source = "git@github.com:theorchard/terraform-chef-bootstrap.git//?ref=3.3.0"

  chef_role         = "qa_neo4j_5_debian_cluster"
  chef_environment  = var.environment
  aws_iam_role_id   = module.neo4j_5_debian_environment.instance_iam_role_name_output
  aws_instance_name = "${var.environment}-${var.service_name}"
}

data "aws_iam_role" "cross_account_neo4j_dns_update_role" {
  provider = aws.networking

  name = "cross-account-neo4j-dns-update"
}

data "aws_iam_policy_document" "assume_cross_account_neo4j_dns_update_role_policy_document" {
  statement {
    effect    = "Allow"
    actions   = ["sts:AssumeRole"]
    resources = [data.aws_iam_role.cross_account_neo4j_dns_update_role.arn]
  }
}

resource "aws_iam_policy" "assume_cross_account_neo4j_dns_update_role_policy" {
  name        = "STS-${var.environment}-${var.service_name}-assume-role-policy"
  description = "Policy to allow the cross-account role to assume the Neo4j Debian cluster role for DNS updates"
  policy      = data.aws_iam_policy_document.assume_cross_account_neo4j_dns_update_role_policy_document.json
}

resource "aws_iam_role_policy_attachment" "qa_neo4j_debian_assume_role_policy" {
  role       = module.neo4j_5_debian_environment.instance_iam_role_name_output
  policy_arn = aws_iam_policy.assume_cross_account_neo4j_dns_update_role_policy.arn
}

# Allow QA cluster to read Prod KMS key to pull backups
data "aws_iam_policy" "prod_neo4j_backup_kms_policy" {
  name = "prod-neo4j-cluster-backup-policy"
}

resource "aws_iam_role_policy_attachment" "prod_kms_backup_policy_attachment_deb" {
  role       = module.neo4j_5_debian_environment.instance_iam_role_name_output
  policy_arn = data.aws_iam_policy.prod_neo4j_backup_kms_policy.arn
}

# Allow QA cluster to read Prod S3 backup location to pull backups
data "aws_iam_policy" "prod_neo4j_backup_s3_readonly_policy" {
  name = "prod-neo4j-cluster-s3-readonly-backup-policy"
}

resource "aws_iam_role_policy_attachment" "prod_s3_backup_readonly_policy_attachment_deb" {
  role       = module.neo4j_5_debian_environment.instance_iam_role_name_output
  policy_arn = data.aws_iam_policy.prod_neo4j_backup_s3_readonly_policy.arn
}

# Allow QA cluster to read restore secrets. Policy managed by
# https://github.com/theorchard/terraform-infra/blob/master/qa/neo4j-cypher-scheduler/integration-test-user/main.tf
data "aws_iam_policy" "secrets_manager_restore_policy" {
  name = "SecretsManager-${var.environment}-neo4j-cluster-restore-policy"
}

resource "aws_iam_role_policy_attachment" "qa_restore_policy_attachment_deb" {
  role       = module.neo4j_5_debian_environment.instance_iam_role_name_output
  policy_arn = data.aws_iam_policy.secrets_manager_restore_policy.arn
}

# Allow shared jenkins node access
data "aws_ec2_managed_prefix_list" "shared_account_prefix_list" {
  name = "shared-orcd-private-subnet-prefix-list"
}

data "aws_ec2_managed_prefix_list" "vpn_sme_internal_primary" {
  name = "vpn-sme-internal-primary"
}

data "aws_ec2_managed_prefix_list" "jump-box-private" {
  name = "shared-orcd-jump-box-private-subnet-prefix-list"
}

# Additional prefix lists for bolt ingress
data "aws_ec2_managed_prefix_list" "bolt_ingress_prefix_lists" {
  for_each = var.bolt_ingress_prefix_lists
  name     = each.value
}

resource "aws_security_group_rule" "allow_shared_jenkins_nodes_ssh" {
  type              = "ingress"
  from_port         = 22
  to_port           = 22
  protocol          = "TCP"
  security_group_id = module.neo4j_5_debian_environment.instance_security_group_id_output
  prefix_list_ids = [
    data.aws_ec2_managed_prefix_list.shared_account_prefix_list.id,
    data.aws_ec2_managed_prefix_list.vpn_sme_internal_primary.id,
    data.aws_ec2_managed_prefix_list.jump-box-private.id,
  ]
  depends_on = [module.neo4j_5_debian_environment]
}

resource "aws_security_group_rule" "allow_shared_jenkins_nodes_neo4j" {
  type              = "ingress"
  from_port         = 7687
  to_port           = 7687
  protocol          = "TCP"
  security_group_id = module.neo4j_5_debian_environment.instance_security_group_id_output
  prefix_list_ids = [
    data.aws_ec2_managed_prefix_list.shared_account_prefix_list.id
  ]
  depends_on = [module.neo4j_5_debian_environment]
}

resource "aws_security_group_rule" "bolt_ingress_prefix_lists" {
  type              = "ingress"
  from_port         = 7687
  to_port           = 7687
  protocol          = "TCP"
  security_group_id = module.neo4j_5_debian_environment.instance_security_group_id_output
  prefix_list_ids = [
    for prefix_list in data.aws_ec2_managed_prefix_list.bolt_ingress_prefix_lists : prefix_list.id
  ]
  depends_on = [module.neo4j_5_debian_environment]
}

# Datadog monitors and dashboards
module "datadog_neo4j_dashboards_and_monitors" {
  source = "git@github.com:theorchard/terraform-datadog.git//modules/neo4j?ref=6.16.1"

  environment                         = var.environment
  service_name                        = var.service_name
  neo4j_major_version_number          = 5
  cpu_warning_recovery_number         = 55
  cpu_warning_number                  = 60
  cpu_critical_recovery_number        = 65
  cpu_critical_number                 = 70
  low_memory_critical_number          = 20
  low_memory_critical_recovery_number = 30
  low_memory_warning_number           = 25
  low_memory_warning_recovery_number  = 35
  disk_space_warning_number           = 90
  disk_space_warning_recovery_number  = 85
  disk_space_critical_number          = 95
  disk_space_critical_recovery_number = 90
  disk_space_evaluation_window        = "last_1h"
  notification_endpoints              = "@slack-monitoring @slack-neo4j-db"
  escalation_notification_endpoints   = "@slack-monitoring @slack-neo4j-db"
}

resource "aws_route53_record" "non_production_route53_record" {
  count   = var.environment != "prod" ? 1 : 0
  name    = "${var.environment}-${var.service_name}"
  zone_id = var.route53_zone_id
  type    = "A"
  ttl     = 60
  # Record value itself is a placeholder
  records = ["1.1.1.1"]

  # Allow DNS record updates via lifecycle hooks without Terraform trying to change things.
  lifecycle {
    ignore_changes = [
      records
    ]
  }
}

resource "aws_route53_record" "non_production_networking_route53_record" {
  provider = aws.networking
  count    = var.environment != "prod" ? 1 : 0

  name    = "${var.environment}-${var.service_name}"
  zone_id = data.aws_route53_zone.networking_route53_zone.zone_id
  type    = "A"
  ttl     = 60
  # Record value itself is a placeholder
  records = [
    "10.100.55.182",
    "10.100.57.176",
    "10.100.59.225",
  ]

  # Allow DNS record updates via lifecycle hooks without Terraform trying to change things.
  lifecycle {
    ignore_changes = [
      records
    ]
  }
}

resource "aws_route53_record" "cluster_discovery" {
  name    = "qa-neo4j-5-cluster-discovery"
  zone_id = var.route53_zone_id
  type    = "A"
  ttl     = 60
  records = [
    "10.100.55.182",
    "10.100.57.176",
    "10.100.59.225",
  ]

  # Allow DNS record updates via lifecycle hooks without Terraform trying to change things.
  lifecycle {
    ignore_changes = [
      records
    ]
  }
}

resource "aws_route53_record" "cluster_discovery_networking" {
  provider = aws.networking

  name    = "qa-neo4j-5-cluster-discovery"
  zone_id = data.aws_route53_zone.networking_route53_zone.zone_id
  type    = "A"
  ttl     = 60
  records = [
    "10.100.55.182",
    "10.100.57.176",
    "10.100.59.225",
  ]

  # Allow DNS record updates via lifecycle hooks without Terraform trying to change things.
  lifecycle {
    ignore_changes = [
      records
    ]
  }
}

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

  environment        = var.environment
  service_name       = var.service_name
  secret_name        = each.value
  application_family = var.application_family
}

resource "aws_route53_record" "cname_route53_record" {
  name    = "${var.environment}-neo4j-cluster"
  zone_id = data.aws_route53_zone.route53_zone.zone_id
  type    = "CNAME"
  ttl     = 60
  records = ["qa-neo4j-5-cluster.theorchard.io"]
}

resource "aws_route53_record" "cname_networking_route53_record" {
  provider = aws.networking

  name    = "${var.environment}-neo4j-cluster"
  zone_id = data.aws_route53_zone.networking_route53_zone.zone_id
  type    = "CNAME"
  ttl     = 60
  records = ["qa-neo4j-5-cluster.theorchard.io"]
}

