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

provider "aws" {
  region = var.aws_region

  default_tags {
    tags = module.default_tags.tags
  }
}

# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "networking-orcd-terraform-state"
    key     = "networking/iam/roles/neo4j-route53-update/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

data "aws_route53_zone" "route53_zone" {
  name = "theorchard.io"
}

data "aws_iam_policy_document" "assume_role_policy" {
  statement {
    sid     = "Neo4jRoute53UpdateAssumeRole"
    actions = ["sts:AssumeRole"]

    principals {
      type = "AWS"

      identifiers = [
        "arn:aws:iam::437795906767:role/qa-neo4j-5-cluster-debian-asg-role",
        "arn:aws:iam::437795906767:role/prod-neo4j-5-cluster-debian-asg-role",
        "arn:aws:iam::437795906767:role/prod-neo4j-5-cluster-debian-13-asg-role",
        "arn:aws:iam::437795906767:role/lambda-qa-networking-lambda-neo4j-dns-update",
        "arn:aws:iam::437795906767:role/lambda-prod-networking-lambda-neo4j-dns-update",
        "arn:aws:iam::437795906767:role/qa-neo4j-5-cluster-debian-13-standalone-testing_x8-asg-role",
        "arn:aws:iam::437795906767:role/qa-neo4j-5-cluster-debian-13-asg-role",
      ]

    }
    condition {
      test     = "StringEquals"
      values   = ["MVbfR8vaLnItbX9nE7"]
      variable = "sts:ExternalId"
    }
  }
}

data "aws_iam_policy_document" "route53_read_write_access" {
  statement {
    sid = "Route53ReadAccess"
    actions = [
      "route53:ListHostedZones",
    ]

    effect = "Allow"

    resources = [
      "*"
    ]
  }

  statement {
    sid = "Route53ChangeResourceRecordSets"
    actions = [
      "route53:ChangeResourceRecordSets",
      "route53:GetHostedZone",
      "route53:ListResourceRecordSets"
    ]

    effect = "Allow"

    resources = [
      data.aws_route53_zone.route53_zone.arn,
    ]
  }
}

resource "aws_iam_policy" "route53_read_write_access" {
  policy      = data.aws_iam_policy_document.route53_read_write_access.json
  name        = "Route53-${var.environment}-shared-RW"
  description = "Read and write access to Route53 for ${var.environment} environment"
}

resource "aws_iam_role" "neo4j_route53_update_role" {
  name               = var.role_name
  assume_role_policy = data.aws_iam_policy_document.assume_role_policy.json
}

resource "aws_iam_role_policy_attachment" "neo4j_route53_update_role_route53_read_write_access" {
  policy_arn = aws_iam_policy.route53_read_write_access.arn
  role       = aws_iam_role.neo4j_route53_update_role.name
}
