#!/bin/bash

# A script to create an EBS volume and attach it to an existing EC2 instance
# using AWS CLI.

# --- Configuration ---
REGION="us-east-1"
VOLUME_SIZE=10 # GB
VOLUME_TYPE="gp3"
VOLUME_NAME="MyCLIEBSVolume"
DEVICE_NAME="/dev/sdf" # Common device name for Linux instances

# --- Prerequisites ---
read -p "Enter the ID of an existing EC2 instance to attach the EBS volume to: " EC2_INSTANCE_ID

if [ -z "$EC2_INSTANCE_ID" ]; then
  echo "EC2 Instance ID cannot be empty. Exiting."
  exit 1
fi

# Validate EC2 instance ID and get its Availability Zone
echo "Validating EC2 instance ID and getting its Availability Zone..."
INSTANCE_AZ=$(aws ec2 describe-instances \
  --instance-ids $EC2_INSTANCE_ID \
  --query 'Reservations[0].Instances[0].Placement.AvailabilityZone' \
  --region $REGION \
  --output text 2>/dev/null)

if [ -z "$INSTANCE_AZ" ] || [ "$INSTANCE_AZ" == "None" ]; then
  echo "Error: EC2 instance '$EC2_INSTANCE_ID' not found or not in a running state in region '$REGION'. Exiting."
  exit 1
fi
echo "EC2 instance '$EC2_INSTANCE_ID' is in Availability Zone: $INSTANCE_AZ"

# --- 1. Create EBS Volume ---
echo -e "\n--- Creating EBS Volume: $VOLUME_NAME in $INSTANCE_AZ ---"
VOLUME_ID=$(aws ec2 create-volume \
  --availability-zone $INSTANCE_AZ \
  --size $VOLUME_SIZE \
  --volume-type $VOLUME_TYPE \
  --tag-specifications "ResourceType=volume,Tags=[{Key=Name,Value=$VOLUME_NAME}]" \
  --region $REGION \
  --query 'VolumeId' --output text)

echo "EBS Volume created with ID: $VOLUME_ID. Waiting for it to be available..."
aws ec2 wait volume-available --volume-ids $VOLUME_ID --region $REGION
echo "EBS Volume is available."

# --- 2. Attach EBS Volume to EC2 Instance ---
echo -e "\n--- Attaching EBS Volume '$VOLUME_ID' to EC2 Instance '$EC2_INSTANCE_ID' ---"
aws ec2 attach-volume \
  --volume-id $VOLUME_ID \
  --instance-id $EC2_INSTANCE_ID \
  --device $DEVICE_NAME \
  --region $REGION

echo "EBS Volume attached. It may take a moment for the OS to recognize the new device."
echo "You can now SSH into your EC2 instance and format/mount the new volume."

read -p "Press Enter to detach and delete the EBS volume..."

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

# Detach EBS Volume
echo "Detaching EBS Volume '$VOLUME_ID' from EC2 Instance '$EC2_INSTANCE_ID' நான்க"
aws ec2 detach-volume \
  --volume-id $VOLUME_ID \
  --instance-id $EC2_INSTANCE_ID \
  --region $REGION

echo "Waiting for volume to be available (detached)..."
aws ec2 wait volume-available --volume-ids $VOLUME_ID --region $REGION
echo "EBS Volume detached."

# Delete EBS Volume
echo "Deleting EBS Volume '$VOLUME_ID' நான்க"
aws ec2 delete-volume \
  --volume-id $VOLUME_ID \
  --region $REGION

echo "EBS Volume deleted."

echo -e "\n--- EBS volume demonstration and cleanup complete ---"
