#!/bin/bash

# Malware Website Crawler - AWS Teardown Script
# This script will destroy all AWS resources created by Terraform

set -e

echo "🚨 WARNING: This script will destroy ALL AWS resources for the Malware Website Crawler!"
echo "This action cannot be undone and will result in permanent data loss."
echo ""
read -p "Are you sure you want to continue? (yes/no): " confirm

if [ "$confirm" != "yes" ]; then
    echo "❌ Teardown cancelled."
    exit 1
fi

echo ""
echo "🔍 Starting AWS resource teardown..."

# Change to terraform directory
cd "$(dirname "$0")/../terraform"

# Check if terraform is initialized
if [ ! -d ".terraform" ]; then
    echo "📦 Initializing Terraform..."
    terraform init
fi

# Get current state
echo "📊 Current Terraform state:"
terraform show -json | jq -r '.values.root_module.resources[] | select(.type != "data") | "\(.type).\(.name)"' 2>/dev/null || echo "No resources found or jq not installed"

echo ""
echo "🗑️  Destroying AWS resources..."

# Run terraform destroy with auto-approve
terraform destroy -auto-approve

echo ""
echo "🧹 Cleaning up local files..."

# Remove terraform state files
rm -f terraform.tfstate*
rm -f .terraform.lock.hcl
rm -rf .terraform/

# Remove any local environment files
rm -f terraform.tfvars
rm -f .env

echo ""
echo "✅ Teardown completed successfully!"
echo ""
echo "📋 Summary of destroyed resources:"
echo "   - VPC and networking components"
echo "   - ECS cluster and services"
echo "   - RDS PostgreSQL database"
echo "   - ElastiCache Redis cluster"
echo "   - S3 buckets (files and logs)"
echo "   - Application Load Balancer"
echo "   - Security groups and IAM roles"
echo "   - CloudWatch log groups"
echo "   - ECR repository"
echo ""
echo "💰 You should see reduced AWS costs in your next billing cycle."
echo "💡 Remember to check your AWS console to ensure all resources are deleted."
