#!/bin/bash

# A script to create a Customer Master Key (CMK) in AWS KMS,
# create an alias, enable key rotation, and then clean up.

# --- Configuration ---
REGION="us-east-1"
CMK_DESCRIPTION="My CLI Test CMK"
CMK_ALIAS="alias/MyCLICMK"
CMK_TAG_KEY="Project"
CMK_TAG_VALUE="KMSDemo"

# --- 1. Create CMK ---
echo "--- Creating Customer Master Key (CMK) ---"
CMK_ID=$(aws kms create-key \
  --description "$CMK_DESCRIPTION" \
  --key-usage ENCRYPT_DECRYPT \
  --key-spec SYMMETRIC_DEFAULT \
  --tags TagKey=$CMK_TAG_KEY,TagValue=$CMK_TAG_VALUE \
  --region $REGION \
  --query 'KeyMetadata.KeyId' --output text)

echo "CMK created with ID: $CMK_ID"

# --- 2. Create Alias for CMK ---
echo -e "\n--- Creating Alias '$CMK_ALIAS' for CMK '$CMK_ID' ---"
aws kms create-alias \
  --alias-name "$CMK_ALIAS" \
  --target-key-id "$CMK_ID" \
  --region $REGION

echo "Alias created."

# --- 3. Enable Key Rotation ---
echo -e "\n--- Enabling automatic key rotation for CMK '$CMK_ID' ---"
aws kms enable-key-rotation \
  --key-id "$CMK_ID" \
  --region $REGION

echo "Key rotation enabled."

echo -e "\n--- KMS CMK setup complete! ---"
echo "CMK ID: $CMK_ID"
echo "CMK Alias: $CMK_ALIAS"

read -p "Press Enter to disable the CMK and schedule it for deletion..."

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

# Disable CMK
echo "Disabling CMK '$CMK_ID' நான"
aws kms disable-key \
  --key-id "$CMK_ID" \
  --region $REGION

echo "CMK disabled."

# Delete Alias
echo "Deleting Alias '$CMK_ALIAS' நான"
aws kms delete-alias \
  --alias-name "$CMK_ALIAS" \
  --region $REGION

echo "Alias deleted."

# Schedule CMK for deletion (minimum 7 days)
echo "Scheduling CMK '$CMK_ID' for deletion in 7 days..."
aws kms schedule-key-deletion \
  --key-id "$CMK_ID" \
  --pending-window-in-days 7 \
  --region $REGION

echo "CMK scheduled for deletion."

echo -e "\n--- KMS CMK demonstration and cleanup complete ---"
