#!/bin/bash

# A script to demonstrate creating a custom CloudWatch metric, publishing data to it,
# and setting up an alarm using AWS CLI.

# --- Configuration ---
REGION="us-east-1"
NAMESPACE="MyApplication"
METRIC_NAME="CustomTransactionCount"
ALARM_NAME="HighCustomTransactionCountAlarm"
THRESHOLD=5
PERIOD=60 # seconds
EVALUATION_PERIODS=1

# --- 1. Publish Custom Metric Data ---
echo "--- Publishing custom metric data to $NAMESPACE/$METRIC_NAME ---"

# Publish a few data points below the threshold
echo "Publishing data points (below threshold)..."
aws cloudwatch put-metric-data \
  --namespace $NAMESPACE \
  --metric-name $METRIC_NAME \
  --value 2 \
  --unit Count \
  --dimensions Service=Auth,Region=$REGION \
  --region $REGION
sleep 5

aws cloudwatch put-metric-data \
  --namespace $NAMESPACE \
  --metric-name $METRIC_NAME \
  --value 3 \
  --unit Count \
  --dimensions Service=Auth,Region=$REGION \
  --region $REGION
sleep 5

# Publish a data point above the threshold to trigger the alarm
echo "Publishing data point (above threshold) to trigger alarm..."
aws cloudwatch put-metric-data \
  --namespace $NAMESPACE \
  --metric-name $METRIC_NAME \
  --value 6 \
  --unit Count \
  --dimensions Service=Auth,Region=$REGION \
  --region $REGION
sleep 5

echo "Metric data published."

# --- 2. Create CloudWatch Alarm ---
echo -e "\n--- Creating CloudWatch Alarm: $ALARM_NAME ---"

# Note: For a real-world scenario, you would typically configure an SNS topic
# for alarm actions. For this demo, we'll create an alarm without an action
# to keep it simple, but it will still change state.
aws cloudwatch put-metric-alarm \
  --alarm-name $ALARM_NAME \
  --alarm-description "Alarm when custom transaction count is too high" \
  --metric-name $METRIC_NAME \
  --namespace $NAMESPACE \
  --statistic Sum \
  --period $PERIOD \
  --threshold $THRESHOLD \
  --comparison-operator GreaterThanThreshold \
  --evaluation-periods $EVALUATION_PERIODS \
  --dimensions Name=Service,Value=Auth Name=Region,Value=$REGION \
  --region $REGION

echo "Alarm '$ALARM_NAME' created."
echo "The alarm will transition to ALARM state if the metric value stays above $THRESHOLD for $EVALUATION_PERIODS period(s) of $PERIOD seconds."
echo "You can check the alarm state in the CloudWatch console."

read -p "Press Enter to clean up resources (delete alarm)..."

# --- Clean Up ---
echo -e "\n--- Deleting CloudWatch Alarm: $ALARM_NAME ---"
aws cloudwatch delete-alarms \
  --alarm-names $ALARM_NAME \
  --region $REGION

echo "Alarm '$ALARM_NAME' deleted."
echo -e "\n--- CloudWatch custom metric and alarm demonstration complete ---"
