# The attribute `${data.aws_caller_identity.current.account_id}` will be current account number.
data "aws_caller_identity" "current" {}

# The attribue `${data.aws_iam_account_alias.current.account_alias}` will be current account alias
data "aws_iam_account_alias" "current" {}

# According to the security requirements we need to send logs into this bucket.
data "aws_s3_bucket" "security_logs" {
  bucket = "security-${local.account_id}-logs"
}

module "aws_accounts_list" {
  source = "../../../modules/iam/aws_accounts_list"
}

module "tags" {
  source = "../../../modules/tags/defaults_plat_env"

  env_prefix    = var.env_prefix
  project_group = local.project_group
}

locals {
  // Constants
  project_group = "whitelist"

  name_prefix         = "${var.env_prefix}-${local.project_group}"
  account_id          = data.aws_caller_identity.current.account_id
  secrets_name_prefix = "${local.project_group}/${var.env_prefix}"
  aggregated_tag      = module.tags.aggregated_tag

  common_tags = module.tags.default_tags

  account_alias = data.aws_iam_account_alias.current.account_alias
  accounts      = module.aws_accounts_list.accounts

  delphi_replica_buckets = formatlist("%s-delphi-whitelist-db", ["dev", "qa", "stage", "prod"])
  delphi_replica_bucket_accounts = {
    "dev-delphi-whitelist-db"   = module.aws_accounts_list.accounts["gdb-delphi-dev"]
    "qa-delphi-whitelist-db"    = module.aws_accounts_list.accounts["gdb-delphi-dev"]
    "stage-delphi-whitelist-db" = module.aws_accounts_list.accounts["gdb-delphi-dev"]
    "prod-delphi-whitelist-db"  = module.aws_accounts_list.accounts["gdb-delphi-prod"]
  }
}

data "aws_vpc" "this" {
  id = "vpc-3563f852"
}

resource "aws_security_group" "dms" {
  name        = "${local.name_prefix}-dms"
  description = "Allow DMS outbound traffic"
  vpc_id      = data.aws_vpc.this.id

  egress {
    from_port        = 0
    to_port          = 0
    protocol         = "-1"
    cidr_blocks      = ["0.0.0.0/0"]
    ipv6_cidr_blocks = ["::/0"]
  }

  tags = {
    Name             = "allow_tls",
    "eiso-exception" = "aws.08.30",
  }
}

resource "aws_security_group_rule" "dms_pg" {
  security_group_id        = "sg-01dd6b7b"
  description              = "Allow access from DMS"
  from_port                = 5432
  to_port                  = 5432
  protocol                 = "tcp"
  type                     = "ingress"
  source_security_group_id = aws_security_group.dms.id
}
