#!/bin/bash

# A script to create a public hosted zone and an A record in Route 53 using AWS CLI.

# --- Configuration ---
REGION="us-east-1"
DOMAIN_NAME="example.com" # !!! IMPORTANT: Replace with a domain you own or a test domain !!!
SUBDOMAIN_NAME="www.$DOMAIN_NAME"
RECORD_IP="192.0.2.1" # A sample IP address

# --- 1. Create Public Hosted Zone ---
echo "--- Creating Public Hosted Zone for $DOMAIN_NAME ---"
HOSTED_ZONE_ID=$(aws route53 create-hosted-zone \
  --name "$DOMAIN_NAME" \
  --caller-reference "$(date +%s)" \
  --hosted-zone-config Comment=\"My CLI Test Hosted Zone\" \
  --region $REGION \
  --query 'HostedZone.Id' --output text)

echo "Hosted Zone created with ID: $HOSTED_ZONE_ID"

# --- 2. Create A Record ---
echo -e "\n--- Creating A record for $SUBDOMAIN_NAME pointing to $RECORD_IP ---"
CHANGE_BATCH_JSON=$(cat <<EOF
{
  "Changes": [
    {
      "Action": "CREATE",
      "ResourceRecordSet": {
        "Name": "$SUBDOMAIN_NAME",
        "Type": "A",
        "TTL": 300,
        "ResourceRecords": [
          {
            "Value": "$RECORD_IP"
          }
        ]
      }
    }
  ]
}
EOF
)

aws route53 change-resource-record-sets \
  --hosted-zone-id $HOSTED_ZONE_ID \
  --change-batch "$CHANGE_BATCH_JSON" \
  --region $REGION

echo "A record created."

# --- 3. Output NS Records ---
echo -e "\n--- Name Servers for your Hosted Zone (update these with your domain registrar) ---"
aws route53 get-hosted-zone \
  --id $HOSTED_ZONE_ID \
  --query 'DelegationSet.NameServers' \
  --region $REGION \
  --output text

echo -e "\n--- Route 53 Hosted Zone setup complete! ---"
echo "Hosted Zone ID: $HOSTED_ZONE_ID"
echo "A Record: $SUBDOMAIN_NAME -> $RECORD_IP"

read -p "Press Enter to delete the A record and Hosted Zone..."

# --- Clean Up ---
echo -e "\n--- Cleaning up resources ---"

# Delete A Record
echo "Deleting A record '$SUBDOMAIN_NAME'"...
CHANGE_BATCH_JSON_DELETE=$(cat <<EOF
{
  "Changes": [
    {
      "Action": "DELETE",
      "ResourceRecordSet": {
        "Name": "$SUBDOMAIN_NAME",
        "Type": "A",
        "TTL": 300,
        "ResourceRecords": [
          {
            "Value": "$RECORD_IP"
          }
        ]
      }
    }
  ]
}
EOF
)

aws route53 change-resource-record-sets \
  --hosted-zone-id $HOSTED_ZONE_ID \
  --change-batch "$CHANGE_BATCH_JSON_DELETE" \
  --region $REGION

echo "A record deleted."

# Delete Hosted Zone
echo "Deleting Hosted Zone '$DOMAIN_NAME'"...
aws route53 delete-hosted-zone \
  --id $HOSTED_ZONE_ID \
  --region $REGION

echo "Hosted Zone deleted."

echo -e "\n--- Route 53 demonstration and cleanup complete ---"
