#!/bin/bash

# Teardown script for AWS Free Tier deployment
# This script safely removes all resources created by the free tier configuration

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Configuration
AWS_REGION="us-east-1"
TERRAFORM_DIR="terraform"
STATE_BUCKET="malware-crawler-terraform-state-free"

echo -e "${BLUE}🗑️  AWS Free Tier Teardown Script${NC}"
echo "=================================="
echo ""

# Function to check if command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Check prerequisites
echo -e "${YELLOW}🔍 Checking prerequisites...${NC}"

if ! command_exists aws; then
    echo -e "${RED}❌ AWS CLI not found. Please install it first.${NC}"
    exit 1
fi

if ! command_exists terraform; then
    echo -e "${RED}❌ Terraform not found. Please install it first.${NC}"
    exit 1
fi

echo -e "${GREEN}✅ Prerequisites check passed${NC}"
echo ""

# Check AWS credentials
echo -e "${YELLOW}🔐 Checking AWS credentials...${NC}"
if ! aws sts get-caller-identity >/dev/null 2>&1; then
    echo -e "${RED}❌ AWS credentials not configured. Please run 'aws configure' first.${NC}"
    exit 1
fi

ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
echo -e "${GREEN}✅ AWS credentials valid (Account: $ACCOUNT_ID)${NC}"
echo ""

# Confirmation prompt
echo -e "${RED}⚠️  WARNING: This will delete ALL resources created by the free tier deployment!${NC}"
echo -e "${YELLOW}This includes:${NC}"
echo "   - ECS Cluster and Service"
echo "   - RDS Database (with data loss!)"
echo "   - ElastiCache Redis (with data loss!)"
echo "   - S3 Buckets (with data loss!)"
echo "   - ECR Repository"
echo "   - CloudWatch Logs"
echo "   - Security Groups"
echo "   - IAM Roles"
echo ""
read -p "Are you sure you want to continue? (yes/no): " confirm

if [[ $confirm != "yes" ]]; then
    echo -e "${YELLOW}❌ Teardown cancelled by user${NC}"
    exit 0
fi

echo ""
echo -e "${BLUE}🚀 Starting teardown process...${NC}"
echo ""

# Change to terraform directory
cd "$TERRAFORM_DIR"

# Check if terraform is initialized
if [ ! -d ".terraform" ]; then
    echo -e "${YELLOW}🔧 Initializing Terraform...${NC}"
    terraform init
fi

# Check if state file exists
if [ ! -f "terraform.tfstate" ]; then
    echo -e "${YELLOW}⚠️  No Terraform state file found. Attempting to import existing resources...${NC}"
    
    # Try to discover and import existing resources
    echo -e "${YELLOW}🔍 Discovering existing resources...${NC}"
    
    # ECS Cluster
    ECS_CLUSTER=$(aws ecs list-clusters --query 'clusterArns[?contains(@, `malware-crawler-cluster-free`)]' --output text)
    if [ ! -z "$ECS_CLUSTER" ]; then
        echo -e "${GREEN}✅ Found ECS Cluster: $ECS_CLUSTER${NC}"
    fi
    
    # RDS Instance
    RDS_INSTANCE=$(aws rds describe-db-instances --query 'DBInstances[?contains(DBInstanceIdentifier, `malware-crawler-db-free`)].[DBInstanceIdentifier]' --output text)
    if [ ! -z "$RDS_INSTANCE" ]; then
        echo -e "${GREEN}✅ Found RDS Instance: $RDS_INSTANCE${NC}"
    fi
    
    # ElastiCache Redis
    REDIS_CLUSTER=$(aws elasticache describe-replication-groups --query 'ReplicationGroups[?contains(ReplicationGroupId, `malware-crawler-redis-free`)].[ReplicationGroupId]' --output text)
    if [ ! -z "$REDIS_CLUSTER" ]; then
        echo -e "${GREEN}✅ Found Redis Cluster: $REDIS_CLUSTER${NC}"
    fi
    
    # S3 Buckets
    S3_BUCKETS=$(aws s3 ls | grep "malware-crawler.*free" | awk '{print $3}')
    if [ ! -z "$S3_BUCKETS" ]; then
        echo -e "${GREEN}✅ Found S3 Buckets: $S3_BUCKETS${NC}"
    fi
    
    echo -e "${YELLOW}⚠️  Some resources may need to be deleted manually.${NC}"
    echo ""
fi

# Run terraform destroy
echo -e "${YELLOW}🗑️  Running Terraform destroy...${NC}"
echo ""

# First, try to destroy with auto-approve
if terraform destroy -auto-approve; then
    echo -e "${GREEN}✅ Terraform destroy completed successfully${NC}"
else
    echo -e "${YELLOW}⚠️  Terraform destroy had issues. Attempting manual cleanup...${NC}"
    
    # Manual cleanup of resources that might not be in state
    echo -e "${YELLOW}🧹 Manual cleanup of remaining resources...${NC}"
    
    # Stop ECS services
    echo -e "${YELLOW}🛑 Stopping ECS services...${NC}"
    aws ecs list-services --cluster malware-crawler-cluster-free --query 'serviceArns[]' --output text | while read service; do
        if [ ! -z "$service" ]; then
            echo "   Stopping service: $service"
            aws ecs update-service --cluster malware-crawler-cluster-free --service "$service" --desired-count 0
            aws ecs delete-service --cluster malware-crawler-cluster-free --service "$service"
        fi
    done
    
    # Delete ECS cluster
    echo -e "${YELLOW}🗑️  Deleting ECS cluster...${NC}"
    aws ecs delete-cluster --cluster malware-crawler-cluster-free 2>/dev/null || echo "   Cluster already deleted or doesn't exist"
    
    # Delete RDS instance
    echo -e "${YELLOW}🗑️  Deleting RDS instance...${NC}"
    aws rds delete-db-instance --db-instance-identifier malware-crawler-db-free --skip-final-snapshot 2>/dev/null || echo "   RDS instance already deleted or doesn't exist"
    
    # Delete ElastiCache Redis
    echo -e "${YELLOW}🗑️  Deleting Redis cluster...${NC}"
    aws elasticache delete-replication-group --replication-group-id malware-crawler-redis-free 2>/dev/null || echo "   Redis cluster already deleted or doesn't exist"
    
    # Delete S3 buckets
    echo -e "${YELLOW}🗑️  Deleting S3 buckets...${NC}"
    aws s3 ls | grep "malware-crawler.*free" | awk '{print $3}' | while read bucket; do
        if [ ! -z "$bucket" ]; then
            echo "   Deleting bucket: $bucket"
            aws s3 rb "s3://$bucket" --force 2>/dev/null || echo "   Bucket already deleted or doesn't exist"
        fi
    done
    
    # Delete ECR repository
    echo -e "${YELLOW}🗑️  Deleting ECR repository...${NC}"
    aws ecr delete-repository --repository-name malware-crawler-app-free --force 2>/dev/null || echo "   ECR repository already deleted or doesn't exist"
    
    # Delete CloudWatch log groups
    echo -e "${YELLOW}🗑️  Deleting CloudWatch log groups...${NC}"
    aws logs delete-log-group --log-group-name "/ecs/malware-crawler-app-free" 2>/dev/null || echo "   Log group already deleted or doesn't exist"
    
    # Delete security groups
    echo -e "${YELLOW}🗑️  Deleting security groups...${NC}"
    aws ec2 describe-security-groups --query 'SecurityGroups[?contains(GroupName, `malware-crawler.*free`)].GroupId' --output text | while read sg; do
        if [ ! -z "$sg" ]; then
            echo "   Deleting security group: $sg"
            aws ec2 delete-security-group --group-id "$sg" 2>/dev/null || echo "   Security group already deleted or doesn't exist"
        fi
    done
fi

# Clean up local files
echo -e "${YELLOW}🧹 Cleaning up local files...${NC}"
rm -f terraform.tfstate*
rm -rf .terraform/
rm -f terraform.tfvars

echo ""
echo -e "${GREEN}✅ Free tier teardown completed!${NC}"
echo ""
echo -e "${BLUE}📊 Summary:${NC}"
echo "   - ECS Cluster and Service: Deleted"
echo "   - RDS Database: Deleted"
echo "   - ElastiCache Redis: Deleted"
echo "   - S3 Buckets: Deleted"
echo "   - ECR Repository: Deleted"
echo "   - CloudWatch Logs: Deleted"
echo "   - Security Groups: Deleted"
echo "   - Local Terraform files: Cleaned up"
echo ""
echo -e "${YELLOW}💡 Next steps:${NC}"
echo "   1. Check AWS Console to verify all resources are deleted"
echo "   2. Review AWS Billing to ensure no unexpected charges"
echo "   3. Delete any remaining resources manually if needed"
echo ""
echo -e "${GREEN}🎉 Free tier cleanup complete!${NC}"
