#!/bin/bash

# A script to create and configure an S3 bucket for static website hosting.

# --- Configuration ---
# Bucket names must be globally unique.
# Using a random suffix to increase the chance of uniqueness.
RANDOM_SUFFIX=$(head /dev/urandom | tr -dc a-z0-9 | head -c 8)
BUCKET_NAME="my-static-website-bucket-${RANDOM_SUFFIX}"
REGION="us-east-1"
INDEX_DOC="index.html"
ERROR_DOC="error.html"

echo "Using bucket name: $BUCKET_NAME"

# --- 1. Create S3 Bucket ---
echo "Creating S3 bucket..."
aws s3api create-bucket \
  --bucket $BUCKET_NAME \
  --region $REGION

# --- 2. Disable Block Public Access ---
# This is required to make the website publicly accessible.
echo "Updating public access block settings..."
aws s3api put-public-access-block \
  --bucket $BUCKET_NAME \
  --public-access-block-configuration "BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false"

# --- 3. Apply a Public-Read Bucket Policy ---
echo "Applying bucket policy..."
POLICY_JSON=$(cat <<-EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "PublicReadGetObject",
      "Effect": "Allow",
      "Principal": "*",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::$BUCKET_NAME/*"
    }
  ]
}
EOF
)
aws s3api put-bucket-policy --bucket $BUCKET_NAME --policy "$POLICY_JSON"

# --- 4. Configure Static Website Hosting ---
echo "Configuring static website hosting..."
aws s3api put-bucket-website \
  --bucket $BUCKET_NAME \
  --website-configuration "IndexDocument={Suffix=$INDEX_DOC},ErrorDocument={Key=$ERROR_DOC}"

# --- 5. Create and Upload Sample Files ---
echo "Creating and uploading sample index.html and error.html..."
echo "<html><body><h1>Welcome to the S3 Static Website!</h1></body></html>" > $INDEX_DOC
echo "<html><body><h1>404 - Page Not Found</h1></body></html>" > $ERROR_DOC

aws s3 cp $INDEX_DOC s3://$BUCKET_NAME/
aws s3 cp $ERROR_DOC s3://$BUCKET_NAME/

# Clean up local files
rm $INDEX_DOC
rm $ERROR_DOC

# --- 6. Output Website URL ---
WEBSITE_URL="http://${BUCKET_NAME}.s3-website-${REGION}.amazonaws.com"
echo "--- Static website setup complete! ---"
echo "Website URL: $WEBSITE_URL"
