#!/bin/bash

# Create Terraform State from Scratch
# This script helps you create a new Terraform state file for existing resources

set -e

echo "🏗️  Creating Terraform State from Scratch"
echo "========================================"
echo ""
echo "This script will help you create a new Terraform state file"
echo "for your existing AWS resources."
echo ""

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

# Function to backup existing state
backup_existing_state() {
    echo "💾 Backing up existing state files..."
    
    if [ -f "terraform.tfstate" ]; then
        cp terraform.tfstate terraform.tfstate.backup.$(date +%Y%m%d_%H%M%S)
        echo "   Backed up terraform.tfstate"
    fi
    
    if [ -f "terraform.tfstate.backup" ]; then
        cp terraform.tfstate.backup terraform.tfstate.backup.$(date +%Y%m%d_%H%M%S)
        echo "   Backed up terraform.tfstate.backup"
    fi
    
    # Remove existing state files
    rm -f terraform.tfstate*
    rm -rf .terraform/
    
    echo "   Removed existing state files"
    echo ""
}

# Function to initialize fresh Terraform
initialize_terraform() {
    echo "📦 Initializing fresh Terraform..."
    
    # Initialize Terraform
    terraform init
    
    echo "   Terraform initialized successfully"
    echo ""
}

# Function to create minimal terraform.tfvars
create_terraform_tfvars() {
    echo "📝 Creating terraform.tfvars file..."
    
    if [ ! -f "terraform.tfvars" ]; then
        cat > terraform.tfvars << EOF
# Malware Website Crawler Configuration
aws_region = "us-east-1"
environment = "prod"
allowed_ips = ["0.0.0.0/0"]  # Change this to your IP address

# Database Configuration
db_instance_class = "db.t3.micro"

# ECS Configuration
fargate_cpu = 512
fargate_memory = 1024

# Auto Scaling
min_capacity = 1
max_capacity = 3

# Destroy Configuration
enable_s3_force_destroy = false
enable_ecr_force_destroy = false
enable_cloudwatch_cleanup = true
create_final_snapshot = true
EOF
        echo "   Created terraform.tfvars file"
    else
        echo "   terraform.tfvars already exists"
    fi
    echo ""
}

# Function to get current AWS resources
get_current_resources() {
    echo "🔍 Discovering current 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 ""
    
    # Create resources list file
    cat > current_resources.txt << EOF
# Current AWS Resources for Malware Website Crawler
# Generated on: $(date)
# AWS Account: $ACCOUNT_ID
# AWS Region: $REGION

EOF
    
    # 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"
        echo "VPC_ID=$VPC_ID" >> current_resources.txt
        
        # Subnets
        SUBNET_IDS=$(aws ec2 describe-subnets --filters "Name=vpc-id,Values=$VPC_ID" --query "Subnets[].SubnetId" --output text)
        if [ ! -z "$SUBNET_IDS" ]; then
            echo "   Subnet IDs: $SUBNET_IDS"
            echo "SUBNET_IDS=\"$SUBNET_IDS\"" >> current_resources.txt
        fi
        
        # 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"
            echo "IGW_ID=$IGW_ID" >> current_resources.txt
        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 [ ! -z "$NAT_IDS" ] && [ "$NAT_IDS" != "None" ]; then
            echo "   NAT Gateway IDs: $NAT_IDS"
            echo "NAT_IDS=\"$NAT_IDS\"" >> current_resources.txt
        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 "ECS_CLUSTER=$CLUSTER_NAME" >> current_resources.txt
        
        # 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 "ECS_SERVICE=$SERVICE_NAME" >> current_resources.txt
        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" ] && [ ! -z "$RDS_INSTANCE" ]; then
        echo "   RDS Instance: $RDS_INSTANCE"
        echo "RDS_INSTANCE=$RDS_INSTANCE" >> current_resources.txt
    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 "REDIS_GROUP=$REDIS_GROUP" >> current_resources.txt
    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
        echo "   S3 Buckets: $S3_BUCKETS"
        echo "S3_BUCKETS=\"$S3_BUCKETS\"" >> current_resources.txt
    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 "ALB_ARN=$ALB_ARN" >> current_resources.txt
        
        # 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 "TG_ARN=$TG_ARN" >> current_resources.txt
        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 [ ! -z "$SG_IDS" ]; then
        echo "   Security Group IDs: $SG_IDS"
        echo "SG_IDS=\"$SG_IDS\"" >> current_resources.txt
    fi
    echo ""
    
    echo "   Resources list saved to: current_resources.txt"
    echo ""
}

# Function to generate import script
generate_import_script() {
    echo "📜 Generating import script..."
    
    cat > import_resources.sh << 'EOF'
#!/bin/bash

# Auto-generated import script
# Run this script to import all resources into Terraform state

set -e

echo "🔄 Importing resources into Terraform state..."

# Source the resources file
source current_resources.txt

# Import VPC
if [ ! -z "$VPC_ID" ] && [ "$VPC_ID" != "None" ]; then
    echo "Importing VPC: $VPC_ID"
    terraform import aws_vpc.main $VPC_ID
fi

# Import Internet Gateway
if [ ! -z "$IGW_ID" ] && [ "$IGW_ID" != "None" ]; then
    echo "Importing Internet Gateway: $IGW_ID"
    terraform import aws_internet_gateway.main $IGW_ID
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)): ${SUBNET_ARRAY[$i]}"
            terraform import "aws_subnet.public[$i]" "${SUBNET_ARRAY[$i]}"
        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)): ${NAT_ARRAY[$i]}"
            terraform import "aws_nat_gateway.main[$i]" "${NAT_ARRAY[$i]}"
        fi
    done
fi

# Import ECS Cluster
if [ ! -z "$ECS_CLUSTER" ]; then
    echo "Importing ECS Cluster: $ECS_CLUSTER"
    terraform import aws_ecs_cluster.main $ECS_CLUSTER
fi

# Import ECS Service
if [ ! -z "$ECS_CLUSTER" ] && [ ! -z "$ECS_SERVICE" ]; then
    echo "Importing ECS Service: $ECS_CLUSTER/$ECS_SERVICE"
    terraform import aws_ecs_service.main $ECS_CLUSTER/$ECS_SERVICE
fi

# Import RDS Instance
if [ ! -z "$RDS_INSTANCE" ] && [ "$RDS_INSTANCE" != "None" ]; then
    echo "Importing RDS Instance: $RDS_INSTANCE"
    terraform import aws_db_instance.main $RDS_INSTANCE
fi

# Import ElastiCache
if [ ! -z "$REDIS_GROUP" ] && [ "$REDIS_GROUP" != "None" ]; then
    echo "Importing ElastiCache Replication Group: $REDIS_GROUP"
    terraform import aws_elasticache_replication_group.main $REDIS_GROUP
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: $bucket"
            terraform import aws_s3_bucket.files $bucket
        elif [[ "$bucket" == *"logs"* ]]; then
            echo "Importing S3 Logs Bucket: $bucket"
            terraform import aws_s3_bucket.logs $bucket
        fi
    done
fi

# Import Load Balancer
if [ ! -z "$ALB_ARN" ] && [ "$ALB_ARN" != "None" ]; then
    echo "Importing Application Load Balancer: $ALB_ARN"
    terraform import aws_lb.main $ALB_ARN
fi

# Import Target Group
if [ ! -z "$TG_ARN" ] && [ "$TG_ARN" != "None" ]; then
    echo "Importing Target Group: $TG_ARN"
    terraform import aws_lb_target_group.app $TG_ARN
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
            SG_NAME=$(aws ec2 describe-security-groups --group-ids $sg_id --query "SecurityGroups[0].GroupName" --output text 2>/dev/null || echo "")
            echo "Importing Security Group: $SG_NAME ($sg_id)"
            case "$SG_NAME" in
                *"alb"*)
                    terraform import aws_security_group.alb $sg_id
                    ;;
                *"ecs"*)
                    terraform import aws_security_group.ecs_tasks $sg_id
                    ;;
                *"rds"*)
                    terraform import aws_security_group.rds $sg_id
                    ;;
                *"redis"*)
                    terraform import aws_security_group.redis $sg_id
                    ;;
            esac
        fi
    done
fi

echo "✅ Import completed!"
echo ""
echo "Next steps:"
echo "1. Run 'terraform state list' to verify imports"
echo "2. Run 'terraform plan' to see what changes are needed"
echo "3. Run 'terraform destroy' to remove all resources"
EOF

    chmod +x import_resources.sh
    echo "   Generated import_resources.sh script"
    echo ""
}

# Function to provide next steps
provide_next_steps() {
    echo "🎯 Next Steps:"
    echo "=============="
    echo ""
    echo "1. Review the generated files:"
    echo "   - current_resources.txt (list of your AWS resources)"
    echo "   - import_resources.sh (script to import resources)"
    echo "   - terraform.tfvars (Terraform configuration)"
    echo ""
    echo "2. Update terraform.tfvars with your specific settings:"
    echo "   - Change allowed_ips to your IP address"
    echo "   - Adjust region if needed"
    echo "   - Modify resource sizes if needed"
    echo ""
    echo "3. Run the import script:"
    echo "   ./import_resources.sh"
    echo ""
    echo "4. Verify the state:"
    echo "   terraform state list"
    echo ""
    echo "5. Check what changes Terraform wants to make:"
    echo "   terraform plan"
    echo ""
    echo "6. If everything looks good, destroy resources:"
    echo "   terraform destroy"
    echo ""
    echo "⚠️  Important Notes:"
    echo "   - Always run 'terraform plan' before 'terraform destroy'"
    echo "   - Some resources may need manual configuration"
    echo "   - Import order matters for dependent resources"
    echo "   - Keep backups of your state files"
    echo ""
}

# Main execution
echo "🚀 Starting state creation 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

# Backup existing state
backup_existing_state

# Initialize Terraform
initialize_terraform

# Create terraform.tfvars
create_terraform_tfvars

# Get current resources
get_current_resources

# Generate import script
generate_import_script

# Provide next steps
provide_next_steps

echo "🎉 State creation process completed!"
echo ""
echo "📁 Generated files:"
echo "   - current_resources.txt (your AWS resources)"
echo "   - import_resources.sh (import script)"
echo "   - terraform.tfvars (configuration)"
echo ""
echo "💡 Run './import_resources.sh' to import all resources into Terraform state."
