#!/bin/bash

# Malware Website Crawler - Emergency AWS Teardown Script
# This script performs an aggressive cleanup of AWS resources
# Use this when normal teardown fails or you need immediate cost reduction

set -e

echo "🚨 EMERGENCY TEARDOWN MODE 🚨"
echo "=============================="
echo ""
echo "⚠️  WARNING: This script will aggressively destroy AWS resources!"
echo "⚠️  This includes:"
echo "   - Force deletion of S3 buckets with all contents"
echo "   - Force deletion of ECR repositories with all images"
echo "   - Immediate termination of all running instances"
echo "   - Deletion of all data without snapshots"
echo ""
echo "💀 THIS ACTION IS IRREVERSIBLE AND WILL CAUSE DATA LOSS! 💀"
echo ""

read -p "Type 'EMERGENCY' to confirm you understand the risks: " confirm

if [ "$confirm" != "EMERGENCY" ]; then
    echo "❌ Emergency teardown cancelled."
    exit 1
fi

echo ""
echo "🔥 Starting emergency teardown..."

# Set AWS CLI to use aggressive settings
export AWS_CLI_AUTO_PROMPT=off

# Get AWS account ID and region
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
REGION=$(aws configure get region || echo "us-east-1")

echo "📍 AWS Account: $ACCOUNT_ID"
echo "📍 AWS Region: $REGION"
echo ""

# Function to force delete S3 buckets
force_delete_s3_buckets() {
    echo "🗑️  Force deleting S3 buckets..."
    
    # List all buckets with malware-crawler in the name
    BUCKETS=$(aws s3api list-buckets --query "Buckets[?contains(Name, 'malware-crawler')].Name" --output text)
    
    for bucket in $BUCKETS; do
        echo "   Deleting bucket: $bucket"
        
        # Remove all objects and versions
        aws s3 rm s3://$bucket --recursive --quiet || true
        aws s3api delete-bucket --bucket $bucket --quiet || true
    done
    
    echo "✅ S3 buckets force deleted!"
}

# Function to force delete ECR repositories
force_delete_ecr_repositories() {
    echo "🗑️  Force deleting ECR repositories..."
    
    # List ECR repositories
    REPOS=$(aws ecr describe-repositories --query "repositories[?contains(repositoryName, 'malware-crawler')].repositoryName" --output text)
    
    for repo in $REPOS; do
        echo "   Deleting repository: $repo"
        
        # Delete all images
        aws ecr batch-delete-image --repository-name $repo --image-ids imageTag=latest --quiet || true
        aws ecr batch-delete-image --repository-name $repo --image-ids imageDigest=$(aws ecr describe-images --repository-name $repo --query 'imageDetails[0].imageDigest' --output text) --quiet || true
        
        # Delete repository
        aws ecr delete-repository --repository-name $repo --force --quiet || true
    done
    
    echo "✅ ECR repositories force deleted!"
}

# Function to force stop ECS services
force_stop_ecs_services() {
    echo "🗑️  Force stopping ECS services..."
    
    # List ECS clusters
    CLUSTERS=$(aws ecs list-clusters --query "clusterArns[?contains(@, 'malware-crawler')]" --output text)
    
    for cluster in $CLUSTERS; do
        CLUSTER_NAME=$(basename $cluster)
        echo "   Stopping services in cluster: $CLUSTER_NAME"
        
        # List services
        SERVICES=$(aws ecs list-services --cluster $CLUSTER_NAME --query "serviceArns" --output text)
        
        for service in $SERVICES; do
            SERVICE_NAME=$(basename $service)
            echo "     Stopping service: $SERVICE_NAME"
            
            # Update service to 0 desired count
            aws ecs update-service --cluster $CLUSTER_NAME --service $SERVICE_NAME --desired-count 0 --quiet || true
            
            # Stop all tasks
            TASKS=$(aws ecs list-tasks --cluster $CLUSTER_NAME --service-name $SERVICE_NAME --query "taskArns" --output text)
            for task in $TASKS; do
                aws ecs stop-task --cluster $CLUSTER_NAME --task $task --quiet || true
            done
        done
    done
    
    echo "✅ ECS services force stopped!"
}

# Function to force delete RDS instances
force_delete_rds_instances() {
    echo "🗑️  Force deleting RDS instances..."
    
    # List RDS instances
    INSTANCES=$(aws rds describe-db-instances --query "DBInstances[?contains(DBInstanceIdentifier, 'malware-crawler')].DBInstanceIdentifier" --output text)
    
    for instance in $INSTANCES; do
        echo "   Deleting RDS instance: $instance"
        
        # Skip final snapshot and force delete
        aws rds delete-db-instance --db-instance-identifier $instance --skip-final-snapshot --delete-automated-backups --quiet || true
    done
    
    echo "✅ RDS instances force deleted!"
}

# Function to force delete ElastiCache clusters
force_delete_elasticache_clusters() {
    echo "🗑️  Force deleting ElastiCache clusters..."
    
    # List ElastiCache replication groups
    GROUPS=$(aws elasticache describe-replication-groups --query "ReplicationGroups[?contains(ReplicationGroupId, 'malware-crawler')].ReplicationGroupId" --output text)
    
    for group in $GROUPS; do
        echo "   Deleting ElastiCache group: $group"
        
        # Force delete without final snapshot
        aws elasticache delete-replication-group --replication-group-id $group --retain-primary-cluster --quiet || true
    done
    
    echo "✅ ElastiCache clusters force deleted!"
}

# Function to force delete Load Balancers
force_delete_load_balancers() {
    echo "🗑️  Force deleting Load Balancers..."
    
    # List Application Load Balancers
    ALBS=$(aws elbv2 describe-load-balancers --query "LoadBalancers[?contains(LoadBalancerName, 'malware-crawler')].LoadBalancerArn" --output text)
    
    for alb in $ALBS; do
        echo "   Deleting ALB: $alb"
        aws elbv2 delete-load-balancer --load-balancer-arn $alb --quiet || true
    done
    
    echo "✅ Load Balancers force deleted!"
}

# Function to force delete CloudWatch log groups
force_delete_cloudwatch_logs() {
    echo "🗑️  Force deleting CloudWatch log groups..."
    
    # List log groups
    LOG_GROUPS=$(aws logs describe-log-groups --query "logGroups[?contains(logGroupName, 'malware-crawler')].logGroupName" --output text)
    
    for log_group in $LOG_GROUPS; do
        echo "   Deleting log group: $log_group"
        aws logs delete-log-group --log-group-name $log_group --quiet || true
    done
    
    echo "✅ CloudWatch log groups force deleted!"
}

# Execute emergency cleanup
echo "🚀 Executing emergency cleanup procedures..."

force_stop_ecs_services
force_delete_s3_buckets
force_delete_ecr_repositories
force_delete_rds_instances
force_delete_elasticache_clusters
force_delete_load_balancers
force_delete_cloudwatch_logs

echo ""
echo "🔥 Emergency teardown completed!"
echo ""
echo "⚠️  IMPORTANT NOTES:"
echo "   - Some resources may take time to fully delete"
echo "   - Check your AWS console to verify all resources are gone"
echo "   - Monitor your AWS bill for the next few days"
echo "   - Some resources may have dependencies that prevent immediate deletion"
echo ""
echo "💡 Next steps:"
echo "   1. Check AWS console for any remaining resources"
echo "   2. Run 'terraform destroy' if you still have Terraform state"
echo "   3. Contact AWS support if resources won't delete"
echo ""
echo "💰 You should see immediate cost reduction for stopped services."
