data "aws_rds_certificate" "latest" {
  latest_valid_till = true
}

locals {
  # GovCloud and Commercial use different CA certs
  ca_cert_identifier = var.aws_partition == "aws" ? "rds-ca-2019" : "rds-ca-2017"
}

output "ca_cert_identifier" {
  value = {
    "current": local.ca_cert_identifier,
    "latest":  data.aws_rds_certificate.latest.id
  }
}

resource "random_password" "password" {
  keepers          = {
    "version": 1 # increment to change the password
    # n.b. you could add other stuff to make this change automatically, e.g.
    # "instance_type": var.instance_type
    # Would then change this password every time the instance type changes.
  }
  length           = 32
  special          = true
  min_lower = 1
  min_numeric = 1
  min_upper = 1
  min_special = 1
  override_special = "~!@%^()-_+"
}

module "keycloak_db" {
  source = "terraform-aws-modules/rds/aws"
  version = "~> v2.0"

  identifier = var.identifier # this is the RDS identifier, not the DB name
  name = "keycloak" # the DB name

  engine             = "postgres"
  engine_version     = "12.5"
  instance_class     = var.db_instance_type
  allocated_storage  = var.rds_storage
  storage_encrypted  = true
  kms_key_id = module.keycloak_key.key_arn
  ca_cert_identifier = local.ca_cert_identifier

  # NOTE: Do NOT use 'user' as the value for 'username' as it throws:
  # "Error creating DB Instance: InvalidParameterValue: MasterUsername
  # user cannot be used as it is a reserved word used by the engine"
  username = "keycloak"
  password = random_password.password.result

  port     = "5432"
  create_random_password = true
  random_password_length = 32

  vpc_security_group_ids = [ aws_security_group.keycloak_rds_sg.id ]

  backup_window      = "00:00-03:00"
  maintenance_window = "Mon:03:00-Mon:06:00"

  # disable backups to create DB faster
  backup_retention_period = var.environment == "test" ? 0 : 35

  tags = merge(var.standard_tags, var.tags)

  enabled_cloudwatch_logs_exports = ["postgresql", "upgrade"]

  # DB subnet group
  subnet_ids = var.private_subnets

  # DB parameter group
  family = "postgres12"

  # DB option group
  major_engine_version = "12"

  # Snapshot name upon DB deletion
  final_snapshot_identifier = "${var.identifier}-final-snapshot"

  # Database Deletion Protection
  deletion_protection = var.instance_termination_protection
}
