# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "gdb-delphi-prod-tfstate"
    key     = "prod/crm-fivetran-connector/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
    profile = "gdb-delphi-prod"
  }
}

provider "aws" {
  region  = var.aws_region
  profile = "gdb-delphi-prod"

  default_tags {
    tags = module.default_tags.tags
  }
}

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


data "fivetran_group" "this" {
  id = var.destination_group_id
}

resource "fivetran_connector" "this" {
  for_each = var.table_pattern_mapping
  group_id = data.fivetran_group.this.id
  service  = "s3"

  destination_schema {
    name  = var.destination_schema
    table = each.key
  }

  config {
    role_arn = aws_iam_role.this.arn
    bucket   = var.bucket
    prefix   = var.prefix
    pattern  = each.value
  }
}

/* resource "fivetran_connector_schedule" "this" {
  connector_id      = fivetran_connector.this.id
  sync_frequency    = 5
  pause_after_trial = false
} */

data "aws_iam_policy_document" "aws_role_trusted_entities" {
  statement {
    actions = ["sts:AssumeRole"]
    effect  = "Allow"
    principals {
      type        = "AWS"
      identifiers = ["arn:aws:iam::${var.fivetran_aws_account_id}:root"]
    }
    condition {
      test     = "StringEquals"
      variable = "sts:ExternalId"
      values   = [data.fivetran_group.this.id]
    }
  }

}

resource "aws_iam_role" "this" {
  name               = "${var.environment}-${var.application_family}-${var.service_name}"
  assume_role_policy = data.aws_iam_policy_document.aws_role_trusted_entities.json
}

module "iam_s3_access_policy_document" {
  source = "git@github.com:theorchard/terraform-iam-policy-templates.git//documents/s3/buckets_with_prefixes?ref=0.3.0"
  buckets = [
    { bucket = var.bucket, prefixes = [var.prefix] }
  ]
  action_types = ["read"]
}

resource "aws_iam_role_policy" "this" {
  role   = aws_iam_role.this.id
  policy = module.iam_s3_access_policy_document.policy.json
}
