#!/bin/bash

# A script to launch a basic EC2 instance, create necessary prerequisites,
# and then clean up all resources using AWS CLI.

# --- Configuration ---
REGION="us-east-1"
INSTANCE_TYPE="t2.micro"
KEY_PAIR_NAME="MyCLIKeyPair"
SECURITY_GROUP_NAME="MyCLISecurityGroup"
VPC_ID="" # Will be dynamically determined
SUBNET_ID="" # Will be dynamically determined

# --- 1. Get Latest Amazon Linux 2 AMI ID ---
echo "--- Finding latest Amazon Linux 2 AMI ID ---"
AMI_ID=$(aws ec2 describe-images \
  --owners amazon \
  --filters "Name=name,Values=amzn2-ami-hvm-*-x86_64-gp2" "Name=state,Values=available" \
  --query "sort_by(Images, &CreationDate)[-1].ImageId" \
  --region $REGION \
  --output text)

if [ -z "$AMI_ID" ]; then
  echo "Error: Could not find a suitable AMI. Exiting."
  exit 1
fi
echo "Found AMI ID: $AMI_ID"

# --- 2. Create EC2 Key Pair ---
echo -e "\n--- Creating EC2 Key Pair: $KEY_PAIR_NAME ---"
aws ec2 create-key-pair \
  --key-name $KEY_PAIR_NAME \
  --query 'KeyMaterial' \
  --output text > $KEY_PAIR_NAME.pem

chmod 400 $KEY_PAIR_NAME.pem
echo "Key pair '$KEY_PAIR_NAME.pem' created. Remember to keep it secure."

# --- 3. Create Security Group ---
echo -e "\n--- Creating Security Group: $SECURITY_GROUP_NAME ---"
# Get default VPC ID
VPC_ID=$(aws ec2 describe-vpcs \
  --filters "Name=is-default,Values=true" \
  --query "Vpcs[0].VpcId" \
  --region $REGION \
  --output text)

if [ -z "$VPC_ID" ]; then
  echo "Error: Could not find a default VPC. Please specify VPC_ID and SUBNET_ID manually."
  exit 1
fi
echo "Using Default VPC ID: $VPC_ID"

SG_ID=$(aws ec2 create-security-group \
  --group-name $SECURITY_GROUP_NAME \
  --description "Allow SSH and HTTP access" \
  --vpc-id $VPC_ID \
  --region $REGION \
  --query 'GroupId' --output text)

# Authorize SSH (port 22)
aws ec2 authorize-security-group-ingress \
  --group-id $SG_ID \
  --protocol tcp \
  --port 22 \
  --cidr 0.0.0.0/0 \
  --region $REGION

# Authorize HTTP (port 80)
aws ec2 authorize-security-group-ingress \
  --group-id $SG_ID \
  --protocol tcp \
  --port 80 \
  --cidr 0.0.0.0/0 \
  --region $REGION

echo "Security Group '$SECURITY_GROUP_NAME' created with ID: $SG_ID"

# Get a default subnet ID in the default VPC
SUBNET_ID=$(aws ec2 describe-subnets \
  --filters "Name=vpc-id,Values=$VPC_ID" "Name=default-for-az,Values=true" \
  --query "Subnets[0].SubnetId" \
  --region $REGION \
  --output text)

if [ -z "$SUBNET_ID" ]; then
  echo "Error: Could not find a default subnet. Please specify SUBNET_ID manually."
  exit 1
fi
echo "Using Default Subnet ID: $SUBNET_ID"

# --- 4. Launch EC2 Instance ---
echo -e "\n--- Launching EC2 Instance ---"
INSTANCE_ID=$(aws ec2 run-instances \
  --image-id $AMI_ID \
  --instance-type $INSTANCE_TYPE \
  --key-name $KEY_PAIR_NAME \
  --security-group-ids $SG_ID \
  --subnet-id $SUBNET_ID \
  --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=MyCLIInstance}]" \
  --region $REGION \
  --query 'Instances[0].InstanceId' --output text)

echo "Instance '$INSTANCE_ID' launched. Waiting for it to be running..."
aws ec2 wait instance-running --instance-ids $INSTANCE_ID --region $REGION
echo "Instance is running."

# --- 5. Output Public IP ---
PUBLIC_IP=$(aws ec2 describe-instances \
  --instance-ids $INSTANCE_ID \
  --query 'Reservations[0].Instances[0].PublicIpAddress' \
  --region $REGION \
  --output text)

echo -e "\n--- EC2 Instance Launched Successfully! ---"
echo "Instance ID: $INSTANCE_ID"
echo "Public IP Address: $PUBLIC_IP"
echo "You can SSH into your instance using: ssh -i $KEY_PAIR_NAME.pem ec2-user@$PUBLIC_IP"
echo "Or access a web server on http://$PUBLIC_IP"

read -p "Press Enter to terminate the instance and clean up resources..."

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

# Terminate instance
echo "Terminating instance '$INSTANCE_ID' நான்குக"
aws ec2 terminate-instances \
  --instance-ids $INSTANCE_ID \
  --region $REGION

echo "Waiting for instance to be terminated..."
aws ec2 wait instance-terminated --instance-ids $INSTANCE_ID --region $REGION
echo "Instance terminated."

# Delete Security Group
echo "Deleting Security Group '$SECURITY_GROUP_NAME' நான்குக"
aws ec2 delete-security-group \
  --group-id $SG_ID \
  --region $REGION

echo "Security Group deleted."

# Delete Key Pair
echo "Deleting Key Pair '$KEY_PAIR_NAME' நான்குக"
aws ec2 delete-key-pair \
  --key-name $KEY_PAIR_NAME \
  --region $REGION

rm $KEY_PAIR_NAME.pem
echo "Key Pair deleted."

echo -e "\n--- EC2 instance demonstration and cleanup complete ---"
