provider "aws" {
  region = var.aws_region
}

terraform {
  backend "s3" {
    bucket  = "dev-orcd-terraform-state"
    key     = "dev/ds-moments/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

data "aws_caller_identity" "current" {}

resource "aws_security_group" "ds_moments_pipeline_security_group" {
  name        = "${var.environment}-${var.service_name}-security-group"
  description = "Security group for ${var.environment}-${var.service_name} Batch job"
  vpc_id      = var.vpc_id

  tags = local.tags
}

resource "aws_security_group_rule" "ds_moments_pipeline_security_group_egress_rule" {
  type              = "egress"
  from_port         = 0
  to_port           = 0
  protocol          = "-1"
  cidr_blocks       = ["0.0.0.0/0"]
  security_group_id = aws_security_group.ds_moments_pipeline_security_group.id
}

# Compute environment
resource "aws_batch_compute_environment" "ds_moments_pipeline_batch_compute" {
  compute_environment_name = "${var.environment}-${var.service_name}-compute"

  compute_resources {
    max_vcpus = 80

    security_group_ids = [aws_security_group.ds_moments_pipeline_security_group.id] # required
    subnets            = var.vpc_subnet_ids                                         # required

    type = "FARGATE"
  }
  # seems that all compute environments share this single role
  service_role = "arn:aws:iam::103233932089:role/service-role/AWSBatchServiceRole"
  type         = "MANAGED"

  tags = local.tags
}

# Job queue
resource "aws_batch_job_queue" "ds_moments_pipeline_queue" {
  name     = "${var.environment}-${var.service_name}-batch-queue"
  state    = "ENABLED"
  priority = 1
  compute_environments = [
    aws_batch_compute_environment.ds_moments_pipeline_batch_compute.arn
  ]

  tags = local.tags
}
