# Terraform configuration to create and configure an S3 bucket for static website hosting.

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

# Generate a random suffix to ensure the bucket name is unique
resource "random_pet" "bucket_suffix" {
  length = 2
}

# --- S3 Bucket for Website ---
resource "aws_s3_bucket" "website" {
  bucket = "my-static-website-bucket-tf-${random_pet.bucket_suffix.id}"

  tags = {
    Name        = "Static Website Bucket (Terraform)"
    Environment = "Public"
  }
}

# --- Configure Public Access ---
# This resource manages the S3 Block Public Access settings.
# We need to turn these off to allow public access for the website.
resource "aws_s3_bucket_public_access_block" "website" {
  bucket = aws_s3_bucket.website.id

  block_public_acls       = false
  block_public_policy     = false
  ignore_public_acls      = false
  restrict_public_buckets = false
}

# --- Apply Public-Read Bucket Policy ---
# This policy allows anyone to read objects from the bucket.
resource "aws_s3_bucket_policy" "website" {
  bucket = aws_s3_bucket.website.id

  policy = jsonencode({
    Version = "2012-10-17",
    Statement = [
      {
        Sid       = "PublicReadGetObject",
        Effect    = "Allow",
        Principal = "*",
        Action    = "s3:GetObject",
        Resource  = "${aws_s3_bucket.website.arn}/*"
      }
    ]
  })

  # Depends on the public access block being configured first
  depends_on = [aws_s3_bucket_public_access_block.website]
}

# --- Configure Static Website Hosting ---
resource "aws_s3_bucket_website_configuration" "website" {
  bucket = aws_s3_bucket.website.id

  index_document {
    suffix = "index.html"
  }

  error_document {
    key = "error.html"
  }

  depends_on = [aws_s3_bucket_policy.website]
}

# --- Upload Sample Files ---
resource "aws_s3_object" "index" {
  bucket       = aws_s3_bucket.website.id
  key          = "index.html"
  source       = "./index.html"
  content_type = "text/html"
  # Use etag to detect file changes
  etag = filemd5("./index.html")
}

resource "aws_s3_object" "error" {
  bucket       = aws_s3_bucket.website.id
  key          = "error.html"
  source       = "./error.html"
  content_type = "text/html"
  # Use etag to detect file changes
  etag = filemd5("./error.html")
}

# --- Create local files for Terraform to upload ---
resource "local_file" "index_html" {
  content  = "<html><body><h1>Welcome to the S3 Static Website! (Managed by Terraform)</h1></body></html>"
  filename = "${path.module}/index.html"
}

resource "local_file" "error_html" {
  content  = "<html><body><h1>404 - Page Not Found (Managed by Terraform)</h1></body></html>"
  filename = "${path.module}/error.html"
}


# --- Output Website URL ---
output "website_url" {
  value       = aws_s3_bucket_website_configuration.website.website_endpoint
  description = "The URL of the static website"
}

output "bucket_name" {
  value       = aws_s3_bucket.website.bucket
  description = "The name of the S3 bucket"
}
