#!/bin/bash

# Import Existing AWS Resources into Terraform State
# This script helps you import already-deployed resources into Terraform state

set -e

echo "🔄 Importing Existing AWS Resources into Terraform State"
echo "======================================================="
echo ""
echo "This script will help you import your existing AWS resources"
echo "into Terraform state so you can manage them with terraform destroy."
echo ""

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

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

# Function to get resource IDs
get_resource_ids() {
    echo "🔍 Discovering existing AWS resources..."
    
    # 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 ""
    
    # VPC Resources
    echo "🌐 VPC Resources:"
    VPC_ID=$(aws ec2 describe-vpcs --filters "Name=tag:Project,Values=MalwareWebsiteCrawler" --query "Vpcs[0].VpcId" --output text 2>/dev/null || echo "")
    if [ "$VPC_ID" != "None" ] && [ "$VPC_ID" != "" ]; then
        echo "   VPC ID: $VPC_ID"
        
        # Subnets
        SUBNET_IDS=$(aws ec2 describe-subnets --filters "Name=vpc-id,Values=$VPC_ID" --query "Subnets[].SubnetId" --output text)
        echo "   Subnet IDs: $SUBNET_IDS"
        
        # Internet Gateway
        IGW_ID=$(aws ec2 describe-internet-gateways --filters "Name=attachment.vpc-id,Values=$VPC_ID" --query "InternetGateways[0].InternetGatewayId" --output text 2>/dev/null || echo "")
        if [ "$IGW_ID" != "None" ] && [ "$IGW_ID" != "" ]; then
            echo "   Internet Gateway ID: $IGW_ID"
        fi
        
        # NAT Gateways
        NAT_IDS=$(aws ec2 describe-nat-gateways --filter "Name=vpc-id,Values=$VPC_ID" --query "NatGateways[].NatGatewayId" --output text 2>/dev/null || echo "")
        if [ "$NAT_IDS" != "None" ] && [ "$NAT_IDS" != "" ]; then
            echo "   NAT Gateway IDs: $NAT_IDS"
        fi
    fi
    echo ""
    
    # ECS Resources
    echo "🐳 ECS Resources:"
    ECS_CLUSTER=$(aws ecs list-clusters --query "clusterArns[?contains(@, 'malware-crawler')]" --output text 2>/dev/null || echo "")
    if [ "$ECS_CLUSTER" != "" ]; then
        CLUSTER_NAME=$(basename $ECS_CLUSTER)
        echo "   ECS Cluster: $CLUSTER_NAME"
        
        # ECS Service
        ECS_SERVICE=$(aws ecs list-services --cluster $CLUSTER_NAME --query "serviceArns[?contains(@, 'malware-crawler')]" --output text 2>/dev/null || echo "")
        if [ "$ECS_SERVICE" != "" ]; then
            SERVICE_NAME=$(basename $ECS_SERVICE)
            echo "   ECS Service: $SERVICE_NAME"
        fi
        
        # Task Definition
        TASK_DEF=$(aws ecs list-task-definitions --family-prefix malware-crawler --query "taskDefinitionArns[0]" --output text 2>/dev/null || echo "")
        if [ "$TASK_DEF" != "None" ] && [ "$TASK_DEF" != "" ]; then
            echo "   Task Definition: $TASK_DEF"
        fi
    fi
    echo ""
    
    # RDS Resources
    echo "🗄️  RDS Resources:"
    RDS_INSTANCE=$(aws rds describe-db-instances --query "DBInstances[?contains(DBInstanceIdentifier, 'malware-crawler')].DBInstanceIdentifier" --output text 2>/dev/null || echo "")
    if [ "$RDS_INSTANCE" != "None" ] && [ "$RDS_INSTANCE" != "" ]; then
        echo "   RDS Instance: $RDS_INSTANCE"
    fi
    echo ""
    
    # ElastiCache Resources
    echo "🔴 ElastiCache Resources:"
    REDIS_GROUP=$(aws elasticache describe-replication-groups --query "ReplicationGroups[?contains(ReplicationGroupId, 'malware-crawler')].ReplicationGroupId" --output text 2>/dev/null || echo "")
    if [ "$REDIS_GROUP" != "None" ] && [ "$REDIS_GROUP" != "" ]; then
        echo "   Redis Group: $REDIS_GROUP"
    fi
    echo ""
    
    # S3 Resources
    echo "💾 S3 Resources:"
    S3_BUCKETS=$(aws s3api list-buckets --query "Buckets[?contains(Name, 'malware-crawler')].Name" --output text 2>/dev/null || echo "")
    if [ "$S3_BUCKETS" != "" ]; then
        echo "   S3 Buckets: $S3_BUCKETS"
    fi
    echo ""
    
    # Load Balancer Resources
    echo "⚖️  Load Balancer Resources:"
    ALB_ARN=$(aws elbv2 describe-load-balancers --query "LoadBalancers[?contains(LoadBalancerName, 'malware-crawler')].LoadBalancerArn" --output text 2>/dev/null || echo "")
    if [ "$ALB_ARN" != "None" ] && [ "$ALB_ARN" != "" ]; then
        echo "   ALB ARN: $ALB_ARN"
        
        # Target Group
        TG_ARN=$(aws elbv2 describe-target-groups --query "TargetGroups[?contains(TargetGroupName, 'malware-crawler')].TargetGroupArn" --output text 2>/dev/null || echo "")
        if [ "$TG_ARN" != "None" ] && [ "$TG_ARN" != "" ]; then
            echo "   Target Group ARN: $TG_ARN"
        fi
    fi
    echo ""
    
    # Security Groups
    echo "🔒 Security Groups:"
    SG_IDS=$(aws ec2 describe-security-groups --filters "Name=group-name,Values=*malware-crawler*" --query "SecurityGroups[].GroupId" --output text 2>/dev/null || echo "")
    if [ "$SG_IDS" != "" ]; then
        echo "   Security Group IDs: $SG_IDS"
    fi
    echo ""
}

# Function to import resources
import_resources() {
    echo "📥 Importing resources into Terraform state..."
    echo ""
    
    # Get resource IDs
    get_resource_ids
    
    echo "🔄 Starting import process..."
    echo ""
    
    # Import VPC
    if [ ! -z "$VPC_ID" ] && [ "$VPC_ID" != "None" ]; then
        echo "Importing VPC..."
        terraform import aws_vpc.main $VPC_ID || echo "VPC import failed or already exists"
    fi
    
    # Import Internet Gateway
    if [ ! -z "$IGW_ID" ] && [ "$IGW_ID" != "None" ]; then
        echo "Importing Internet Gateway..."
        terraform import aws_internet_gateway.main $IGW_ID || echo "IGW import failed or already exists"
    fi
    
    # Import Subnets
    if [ ! -z "$SUBNET_IDS" ]; then
        IFS=' ' read -ra SUBNET_ARRAY <<< "$SUBNET_IDS"
        for i in "${!SUBNET_ARRAY[@]}"; do
            if [ "${SUBNET_ARRAY[$i]}" != "None" ] && [ "${SUBNET_ARRAY[$i]}" != "" ]; then
                echo "Importing Subnet $((i+1))..."
                terraform import "aws_subnet.public[$i]" "${SUBNET_ARRAY[$i]}" || echo "Subnet $((i+1)) import failed or already exists"
            fi
        done
    fi
    
    # Import NAT Gateways
    if [ ! -z "$NAT_IDS" ]; then
        IFS=' ' read -ra NAT_ARRAY <<< "$NAT_IDS"
        for i in "${!NAT_ARRAY[@]}"; do
            if [ "${NAT_ARRAY[$i]}" != "None" ] && [ "${NAT_ARRAY[$i]}" != "" ]; then
                echo "Importing NAT Gateway $((i+1))..."
                terraform import "aws_nat_gateway.main[$i]" "${NAT_ARRAY[$i]}" || echo "NAT Gateway $((i+1)) import failed or already exists"
            fi
        done
    fi
    
    # Import ECS Cluster
    if [ ! -z "$CLUSTER_NAME" ]; then
        echo "Importing ECS Cluster..."
        terraform import aws_ecs_cluster.main $CLUSTER_NAME || echo "ECS Cluster import failed or already exists"
    fi
    
    # Import ECS Service
    if [ ! -z "$CLUSTER_NAME" ] && [ ! -z "$SERVICE_NAME" ]; then
        echo "Importing ECS Service..."
        terraform import aws_ecs_service.main $CLUSTER_NAME/$SERVICE_NAME || echo "ECS Service import failed or already exists"
    fi
    
    # Import RDS Instance
    if [ ! -z "$RDS_INSTANCE" ] && [ "$RDS_INSTANCE" != "None" ]; then
        echo "Importing RDS Instance..."
        terraform import aws_db_instance.main $RDS_INSTANCE || echo "RDS Instance import failed or already exists"
    fi
    
    # Import ElastiCache
    if [ ! -z "$REDIS_GROUP" ] && [ "$REDIS_GROUP" != "None" ]; then
        echo "Importing ElastiCache Replication Group..."
        terraform import aws_elasticache_replication_group.main $REDIS_GROUP || echo "ElastiCache import failed or already exists"
    fi
    
    # Import S3 Buckets
    if [ ! -z "$S3_BUCKETS" ]; then
        IFS=' ' read -ra BUCKET_ARRAY <<< "$S3_BUCKETS"
        for bucket in "${BUCKET_ARRAY[@]}"; do
            if [[ "$bucket" == *"files"* ]]; then
                echo "Importing S3 Files Bucket..."
                terraform import aws_s3_bucket.files $bucket || echo "S3 Files Bucket import failed or already exists"
            elif [[ "$bucket" == *"logs"* ]]; then
                echo "Importing S3 Logs Bucket..."
                terraform import aws_s3_bucket.logs $bucket || echo "S3 Logs Bucket import failed or already exists"
            fi
        done
    fi
    
    # Import Load Balancer
    if [ ! -z "$ALB_ARN" ] && [ "$ALB_ARN" != "None" ]; then
        echo "Importing Application Load Balancer..."
        terraform import aws_lb.main $ALB_ARN || echo "ALB import failed or already exists"
    fi
    
    # Import Target Group
    if [ ! -z "$TG_ARN" ] && [ "$TG_ARN" != "None" ]; then
        echo "Importing Target Group..."
        terraform import aws_lb_target_group.app $TG_ARN || echo "Target Group import failed or already exists"
    fi
    
    # Import Security Groups
    if [ ! -z "$SG_IDS" ]; then
        IFS=' ' read -ra SG_ARRAY <<< "$SG_IDS"
        for sg_id in "${SG_ARRAY[@]}"; do
            if [ "$sg_id" != "None" ] && [ "$sg_id" != "" ]; then
                echo "Importing Security Group: $sg_id"
                # Try to match security group names to terraform resources
                SG_NAME=$(aws ec2 describe-security-groups --group-ids $sg_id --query "SecurityGroups[0].GroupName" --output text 2>/dev/null || echo "")
                case "$SG_NAME" in
                    *"alb"*)
                        terraform import aws_security_group.alb $sg_id || echo "ALB Security Group import failed"
                        ;;
                    *"ecs"*)
                        terraform import aws_security_group.ecs_tasks $sg_id || echo "ECS Security Group import failed"
                        ;;
                    *"rds"*)
                        terraform import aws_security_group.rds $sg_id || echo "RDS Security Group import failed"
                        ;;
                    *"redis"*)
                        terraform import aws_security_group.redis $sg_id || echo "Redis Security Group import failed"
                        ;;
                esac
            fi
        done
    fi
    
    echo ""
    echo "✅ Import process completed!"
    echo ""
}

# Function to verify state
verify_state() {
    echo "🔍 Verifying Terraform state..."
    echo ""
    
    # Show current state
    echo "📊 Current Terraform state:"
    terraform state list
    
    echo ""
    echo "📋 State summary:"
    terraform show -json | jq -r '.values.root_module.resources[] | "\(.type).\(.name): \(.values.id // "N/A")"' 2>/dev/null || terraform show
    
    echo ""
    echo "💡 Next steps:"
    echo "   1. Review the state list above"
    echo "   2. Run 'terraform plan' to see what changes Terraform wants to make"
    echo "   3. If everything looks good, you can now use 'terraform destroy'"
    echo ""
}

# Main execution
echo "🚀 Starting resource import process..."
echo ""

# Check AWS CLI
if ! command -v aws &> /dev/null; then
    echo "❌ AWS CLI not found. Please install and configure AWS CLI first."
    exit 1
fi

# Check if AWS credentials are configured
if ! aws sts get-caller-identity &> /dev/null; then
    echo "❌ AWS credentials not configured. Please run 'aws configure' first."
    exit 1
fi

# Run import process
import_resources

# Verify state
verify_state

echo "🎉 Resource import completed successfully!"
echo ""
echo "📝 Important notes:"
echo "   - Some resources may need manual configuration in terraform files"
echo "   - Run 'terraform plan' to see what changes are needed"
echo "   - You can now use 'terraform destroy' to remove all resources"
echo ""
echo "🔧 If you encounter issues:"
echo "   - Check terraform.tfvars configuration"
echo "   - Verify resource names match your actual AWS resources"
echo "   - Some resources may need to be imported manually"
