#!/bin/bash

# A script to deploy a simple S3 bucket using a CloudFormation template via AWS CLI.

# --- Configuration ---
REGION="us-east-1"
STACK_NAME="MyCLIS3BucketStack"
TEMPLATE_FILE="s3-bucket-template.yaml"
BUCKET_NAME_PREFIX="my-cli-cf-bucket" # Will be suffixed for uniqueness

# --- 1. Create CloudFormation Template File ---
echo "--- Creating CloudFormation template file: $TEMPLATE_FILE ---"
cat > $TEMPLATE_FILE <<EOF
AWSTemplateFormatVersion: '2010-09-09'
Description: A simple S3 bucket CloudFormation template for CLI demo.

Resources:
  MyS3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: ${BUCKET_NAME_PREFIX}-${AWS::AccountId}-${AWS::Region}
      Tags:
        - Key: Environment
          Value: Development
        - Key: Project
          Value: CloudFormationCLIDemo
    DeletionPolicy: Delete # Ensures bucket is deleted with stack

Outputs:
  BucketName:
    Description: Name of the S3 bucket
    Value: !Ref MyS3Bucket
EOF

echo "Template file created."

# --- 2. Create CloudFormation Stack ---
echo -e "\n--- Creating CloudFormation Stack: $STACK_NAME ---"
aws cloudformation create-stack \
  --stack-name $STACK_NAME \
  --template-body file://$TEMPLATE_FILE \
  --region $REGION

echo "Waiting for stack creation to complete..."
aws cloudformation wait stack-create-complete \
  --stack-name $STACK_NAME \
  --region $REGION

echo "Stack '$STACK_NAME' created successfully."

# --- 3. Output Bucket Name ---
echo -e "\n--- Retrieving S3 Bucket Name from Stack Outputs ---"
BUCKET_NAME=$(aws cloudformation describe-stacks \
  --stack-name $STACK_NAME \
  --query 'Stacks[0].Outputs[?OutputKey==`BucketName`].OutputValue' \
  --region $REGION \
  --output text)

echo "S3 Bucket Name: $BUCKET_NAME"

echo -e "\n--- CloudFormation S3 bucket deployment complete! ---"
read -p "Press Enter to delete the CloudFormation stack and clean up..."

# --- Clean Up ---
echo -e "\n--- Deleting CloudFormation Stack: $STACK_NAME ---"
aws cloudformation delete-stack \
  --stack-name $STACK_NAME \
  --region $REGION

echo "Waiting for stack deletion to complete..."
aws cloudformation wait stack-delete-complete \
  --stack-name $STACK_NAME \
  --region $REGION

echo "Stack '$STACK_NAME' deleted successfully."

# Delete local template file
rm $TEMPLATE_FILE
echo "Local template file '$TEMPLATE_FILE' deleted."

echo -e "\n--- CloudFormation S3 bucket demonstration and cleanup complete ---"
