#!/bin/bash

# Manual Import Commands for Existing AWS Resources
# Use this script if the automatic import script doesn't work

echo "🔧 Manual Import Commands for Terraform State"
echo "============================================="
echo ""
echo "This script provides manual import commands for each resource type."
echo "Run these commands one by one, replacing the resource IDs with your actual IDs."
echo ""

# Function to get resource IDs and provide import commands
generate_import_commands() {
    echo "🔍 First, let's get your resource IDs..."
    echo ""
    
    # VPC
    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"
        echo "   Import command: terraform import aws_vpc.main $VPC_ID"
    else
        echo "   VPC ID: Not found"
        echo "   Import command: terraform import aws_vpc.main vpc-xxxxxxxxx"
    fi
    echo ""
    
    # Internet Gateway
    if [ ! -z "$VPC_ID" ] && [ "$VPC_ID" != "None" ]; then
        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"
            echo "   Import command: terraform import aws_internet_gateway.main $IGW_ID"
        else
            echo "   Internet Gateway ID: Not found"
            echo "   Import command: terraform import aws_internet_gateway.main igw-xxxxxxxxx"
        fi
    fi
    echo ""
    
    # Subnets
    if [ ! -z "$VPC_ID" ] && [ "$VPC_ID" != "None" ]; then
        echo "📡 Subnets:"
        SUBNET_IDS=$(aws ec2 describe-subnets --filters "Name=vpc-id,Values=$VPC_ID" --query "Subnets[].SubnetId" --output text)
        if [ ! -z "$SUBNET_IDS" ]; then
            IFS=' ' read -ra SUBNET_ARRAY <<< "$SUBNET_IDS"
            for i in "${!SUBNET_ARRAY[@]}"; do
                echo "   Subnet $((i+1)): ${SUBNET_ARRAY[$i]}"
                echo "   Import command: terraform import \"aws_subnet.public[$i]\" ${SUBNET_ARRAY[$i]}"
            done
        else
            echo "   Subnet IDs: Not found"
            echo "   Import command: terraform import \"aws_subnet.public[0]\" subnet-xxxxxxxxx"
        fi
    fi
    echo ""
    
    # NAT Gateways
    if [ ! -z "$VPC_ID" ] && [ "$VPC_ID" != "None" ]; then
        echo "🌐 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 [ ! -z "$NAT_IDS" ] && [ "$NAT_IDS" != "None" ]; then
            IFS=' ' read -ra NAT_ARRAY <<< "$NAT_IDS"
            for i in "${!NAT_ARRAY[@]}"; do
                echo "   NAT Gateway $((i+1)): ${NAT_ARRAY[$i]}"
                echo "   Import command: terraform import \"aws_nat_gateway.main[$i]\" ${NAT_ARRAY[$i]}"
            done
        else
            echo "   NAT Gateway IDs: Not found"
            echo "   Import command: terraform import \"aws_nat_gateway.main[0]\" nat-xxxxxxxxx"
        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 [ ! -z "$ECS_CLUSTER" ]; then
        CLUSTER_NAME=$(basename $ECS_CLUSTER)
        echo "   ECS Cluster: $CLUSTER_NAME"
        echo "   Import command: terraform import aws_ecs_cluster.main $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 [ ! -z "$ECS_SERVICE" ]; then
            SERVICE_NAME=$(basename $ECS_SERVICE)
            echo "   ECS Service: $SERVICE_NAME"
            echo "   Import command: terraform import aws_ecs_service.main $CLUSTER_NAME/$SERVICE_NAME"
        fi
    else
        echo "   ECS Cluster: Not found"
        echo "   Import command: terraform import aws_ecs_cluster.main malware-crawler-cluster"
    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" ] && [ ! -z "$RDS_INSTANCE" ]; then
        echo "   RDS Instance: $RDS_INSTANCE"
        echo "   Import command: terraform import aws_db_instance.main $RDS_INSTANCE"
    else
        echo "   RDS Instance: Not found"
        echo "   Import command: terraform import aws_db_instance.main malware-crawler-db"
    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" ] && [ ! -z "$REDIS_GROUP" ]; then
        echo "   Redis Group: $REDIS_GROUP"
        echo "   Import command: terraform import aws_elasticache_replication_group.main $REDIS_GROUP"
    else
        echo "   Redis Group: Not found"
        echo "   Import command: terraform import aws_elasticache_replication_group.main malware-crawler-redis"
    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 [ ! -z "$S3_BUCKETS" ]; then
        IFS=' ' read -ra BUCKET_ARRAY <<< "$S3_BUCKETS"
        for bucket in "${BUCKET_ARRAY[@]}"; do
            echo "   S3 Bucket: $bucket"
            if [[ "$bucket" == *"files"* ]]; then
                echo "   Import command: terraform import aws_s3_bucket.files $bucket"
            elif [[ "$bucket" == *"logs"* ]]; then
                echo "   Import command: terraform import aws_s3_bucket.logs $bucket"
            fi
        done
    else
        echo "   S3 Buckets: Not found"
        echo "   Import command: terraform import aws_s3_bucket.files malware-crawler-files-xxxxxxxx"
    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" ] && [ ! -z "$ALB_ARN" ]; then
        echo "   ALB ARN: $ALB_ARN"
        echo "   Import command: terraform import aws_lb.main $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" ] && [ ! -z "$TG_ARN" ]; then
            echo "   Target Group ARN: $TG_ARN"
            echo "   Import command: terraform import aws_lb_target_group.app $TG_ARN"
        fi
    else
        echo "   ALB ARN: Not found"
        echo "   Import command: terraform import aws_lb.main arn:aws:elasticloadbalancing:region:account:loadbalancer/app/malware-crawler-alb/xxxxxxxxx"
    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 [ ! -z "$SG_IDS" ]; then
        IFS=' ' read -ra SG_ARRAY <<< "$SG_IDS"
        for sg_id in "${SG_ARRAY[@]}"; do
            SG_NAME=$(aws ec2 describe-security-groups --group-ids $sg_id --query "SecurityGroups[0].GroupName" --output text 2>/dev/null || echo "")
            echo "   Security Group: $SG_NAME ($sg_id)"
            case "$SG_NAME" in
                *"alb"*)
                    echo "   Import command: terraform import aws_security_group.alb $sg_id"
                    ;;
                *"ecs"*)
                    echo "   Import command: terraform import aws_security_group.ecs_tasks $sg_id"
                    ;;
                *"rds"*)
                    echo "   Import command: terraform import aws_security_group.rds $sg_id"
                    ;;
                *"redis"*)
                    echo "   Import command: terraform import aws_security_group.redis $sg_id"
                    ;;
                *)
                    echo "   Import command: terraform import aws_security_group.unknown $sg_id"
                    ;;
            esac
        done
    else
        echo "   Security Groups: Not found"
        echo "   Import command: terraform import aws_security_group.alb sg-xxxxxxxxx"
    fi
    echo ""
}

# Function to provide step-by-step instructions
provide_instructions() {
    echo "📋 Step-by-Step Import Instructions:"
    echo "===================================="
    echo ""
    echo "1. Navigate to your terraform directory:"
    echo "   cd terraform"
    echo ""
    echo "2. Initialize Terraform (if not already done):"
    echo "   terraform init"
    echo ""
    echo "3. Create terraform.tfvars file with your configuration:"
    echo "   aws_region = \"us-east-1\""
    echo "   environment = \"prod\""
    echo "   allowed_ips = [\"YOUR_IP_ADDRESS/32\"]"
    echo ""
    echo "4. Run the import commands above one by one"
    echo ""
    echo "5. After importing, verify the state:"
    echo "   terraform state list"
    echo ""
    echo "6. Check what changes Terraform wants to make:"
    echo "   terraform plan"
    echo ""
    echo "7. If everything looks good, you can now destroy resources:"
    echo "   terraform destroy"
    echo ""
    echo "⚠️  Important Notes:"
    echo "   - Some resources may need manual configuration in terraform files"
    echo "   - Import order matters for dependent resources"
    echo "   - Always run 'terraform plan' before 'terraform destroy'"
    echo "   - Some resources may need to be imported in a specific order"
    echo ""
}

# Main execution
echo "🚀 Generating manual import commands..."
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

# Generate import commands
generate_import_commands

# Provide instructions
provide_instructions

echo "🎉 Manual import commands generated!"
echo ""
echo "💡 Pro tip: Save this output to a file for reference:"
echo "   ./scripts/manual-import-commands.sh > import-commands.txt"
