provider "aws" {
  region = var.aws_region
}

# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "dev-orcd-terraform-state"
    key     = "dev/kafka-infra/jdbc-source/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

data "aws_caller_identity" "current" {}

module "jdbc_source_country_fargate_environment" {
  source = "git@github.com:theorchard/terraform-fargate.git//?ref=2.3.1"

  environment        = var.environment
  application_family = var.application_family
  # Shortened to accommodate AWS name length limits
  service_name                      = "${var.service_name}-jdbc-ar-ctry"
  non_ecr_image                     = "${data.aws_caller_identity.current.account_id}.dkr.ecr.${var.aws_region}.amazonaws.com/${var.service_name}-jdbc-source-mysql:latest"
  aws_region                        = var.aws_region
  service_platform_version          = "1.4.0"
  desired_task_count                = 1
  minimum_capacity                  = 1
  maximum_capacity                  = 1
  task_cpu                          = 1024
  task_memory                       = 2048
  container_port                    = 8083
  health_check_grace_period_seconds = 300
  blocking_waf_enabled              = true
  health_check_path                 = "/connectors/${var.connector_name}"
  web_service_health_check_command  = "[[ $(curl -s http://localhost:8083/connectors/${var.connector_name}/status | jq -r '.tasks[].state' | sort | uniq) == 'RUNNING' ]] || exit 1"
  vpc_id                            = "vpc-34dbfd51"

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      CONNECT_BOOTSTRAP_SERVERS = var.connect_bootstrap_servers
    },
    {
      SERVICE_NAME = "${var.service_name}-jdbc-ar-ctry"
    },
    {
      DEBUG_MODE = "true"
    },
    {
      AWS_SECRETS_MANAGER = "true"
    },
    {
      DATABASE_CONNECTION_URL = "jdbc:mysql://phys.db.devorch.com:3306/art_relations"
    },
    {
      DATABASE_CATALOG_PATTERN = "art_relations"
    },
    {
      DATABASE_TABLE_WHITELIST = "country"
    },
    {
      MODE = "bulk"
    },
    {
      TOPIC_PREFIX = "jdbc-source-ar-"
    },
    {
      POLL_INTERVAL_MS = 60000
    },
  ]
}

# This rule will allow kafka-connect tasks to communicate with each other in distributed mode
resource "aws_security_group_rule" "allow_intra_cluster_communication" {
  from_port         = 8083
  to_port           = 8083
  protocol          = "tcp"
  security_group_id = module.jdbc_source_country_fargate_environment.fargate_security_group_id
  self              = true
  type              = "ingress"
}
