# Terraform configuration to enable AWS Config.

provider "aws" {
  region = "us-east-1"
}

# --- 1. S3 Bucket for Config Recordings ---
resource "aws_s3_bucket" "config_bucket" {
  bucket = "my-terraform-config-bucket-${data.aws_caller_identity.current.account_id}-${data.aws_region.current.name}"
  acl    = "private" # Best practice
  force_destroy = true # For easy cleanup in demo

  tags = {
    Name = "AWSConfigBucket"
  }
}

resource "aws_s3_bucket_versioning" "config_bucket_versioning" {
  bucket = aws_s3_bucket.config_bucket.id
  versioning_configuration {
    status = "Enabled"
  }
}

# --- 2. IAM Role for AWS Config ---
resource "aws_iam_role" "config_role" {
  name = "MyTerraformConfigRole"

  assume_role_policy = jsonencode({
    Version = "2012-10-17",
    Statement = [
      {
        Effect = "Allow",
        Principal = {
          Service = "config.amazonaws.com"
        },
        Action = "sts:AssumeRole"
      }
    ]
  })
}

resource "aws_iam_role_policy_attachment" "config_role_policy" {
  role       = aws_iam_role.config_role.name
  policy_arn = "arn:aws:iam::aws:policy/AWSConfigRole"
}

# --- 3. Configuration Recorder ---
resource "aws_config_configuration_recorder" "main" {
  name     = "default" # Use default name
  role_arn = aws_iam_role.config_role.arn

  recording_group {
    all_supported = true
    include_global_resource_types = true
  }

  depends_on = [aws_iam_role_policy_attachment.config_role_policy]
}

# --- 4. Delivery Channel ---
resource "aws_config_delivery_channel" "main" {
  name           = "default" # Use default name
  s3_bucket_name = aws_s3_bucket.config_bucket.id
  s3_key_prefix  = "config"

  depends_on = [aws_config_configuration_recorder.main]
}

# Start the recorder (implicitly done by creating the recorder and delivery channel)
resource "aws_config_configuration_recorder_status" "main" {
  name       = aws_config_configuration_recorder.main.name
  is_enabled = true

  depends_on = [aws_config_delivery_channel.main]
}

# Data sources for dynamic bucket name
data "aws_caller_identity" "current" {}
data "aws_region" "current" {}

# --- Outputs ---
output "config_bucket_name" {
  value       = aws_s3_bucket.config_bucket.bucket
  description = "The S3 bucket used for AWS Config recordings."
}

output "config_recorder_name" {
  value       = aws_config_configuration_recorder.main.name
  description = "The name of the AWS Config configuration recorder."
}
