#!/bin/bash

# A script to demonstrate basic SNS topic operations (create, subscribe email, publish, unsubscribe, delete)
# using AWS CLI.

# --- Configuration ---
REGION="us-east-1"
TOPIC_NAME="MyCLISNSTopic"
EMAIL_ADDRESS="your-email@example.com" # !!! IMPORTANT: Replace with your actual email address !!!

# --- 1. Create SNS Topic ---
echo "--- Creating SNS Topic: $TOPIC_NAME ---"
TOPIC_ARN=$(aws sns create-topic \
  --name $TOPIC_NAME \
  --region $REGION \
  --query 'TopicArn' --output text)

echo "Topic created with ARN: $TOPIC_ARN"

# --- 2. Subscribe Email Endpoint ---
echo -e "\n--- Subscribing email address: $EMAIL_ADDRESS to the topic ---"
SUBSCRIPTION_ARN=$(aws sns subscribe \
  --topic-arn $TOPIC_ARN \
  --protocol email \
  --notification-endpoint "$EMAIL_ADDRESS" \
  --region $REGION \
  --query 'SubscriptionArn' --output text)

echo "Subscription initiated. Check your email ($EMAIL_ADDRESS) for a confirmation link."
echo "You MUST click the confirmation link in the email for the subscription to become active."
read -p "Press Enter after you have confirmed the subscription in your email..."

# Verify subscription status (optional, but good practice)
echo -e "\n--- Verifying subscription status ---"
STATUS=$(aws sns get-subscription-attributes \
  --subscription-arn "$SUBSCRIPTION_ARN" \
  --region $REGION \
  --attribute-name \"PendingConfirmation\" \
  --query 'Attributes.PendingConfirmation' --output text)

if [ "$STATUS" == "false" ]; then
  echo "Subscription confirmed successfully."
else
  echo "Subscription is still pending confirmation or failed. Please ensure you confirmed the email."
  echo "Exiting as publishing will not work without a confirmed subscription."
  # Clean up before exiting
  aws sns unsubscribe --subscription-arn "$SUBSCRIPTION_ARN" --region $REGION
  aws sns delete-topic --topic-arn "$TOPIC_ARN" --region $REGION
  exit 1
fi

# --- 3. Publish Message ---
echo -e "\n--- Publishing a message to the topic ---"
MESSAGE_SUBJECT="CLI SNS Test Message"
MESSAGE_BODY="This is a test message sent from the AWS CLI to your email."

aws sns publish \
  --topic-arn $TOPIC_ARN \
  --subject "$MESSAGE_SUBJECT" \
  --message "$MESSAGE_BODY" \
  --region $REGION

echo "Message published. Check your email for the notification."

# --- 4. Unsubscribe Email Endpoint ---
echo -e "\n--- Unsubscribing email address ---"
aws sns unsubscribe \
  --subscription-arn "$SUBSCRIPTION_ARN" \
  --region $REGION

echo "Email address unsubscribed."

# --- 5. Delete SNS Topic ---
echo -e "\n--- Deleting SNS Topic: $TOPIC_NAME ---"
aws sns delete-topic \
  --topic-arn $TOPIC_ARN \
  --region $REGION

echo "Topic $TOPIC_NAME deleted successfully."

echo -e "\n--- SNS publish/subscribe demonstration complete ---"
