#\!/bin/bash

# Cleanup script for removing duplicate HVAC Community Events plugins
# This script removes all but the main plugin before applying fixes

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

# Load environment variables
source "$(dirname "$0")/../.env"

# Check if environment variables are loaded
if [ -z "$UPSKILL_STAGING_IP" ] || [ -z "$UPSKILL_STAGING_SSH_USER" ]; then
    echo -e "${RED}Error: Missing required environment variables${NC}"
    echo "Please ensure .env file exists and contains UPSKILL_STAGING_IP and UPSKILL_STAGING_SSH_USER"
    exit 1
fi

# Set variables
REMOTE_HOST="${UPSKILL_STAGING_IP}"
REMOTE_USER="${UPSKILL_STAGING_SSH_USER}"
REMOTE_PASS="${UPSKILL_STAGING_PASS}"
REMOTE_PATH="/home/974670.cloudwaysapps.com/uberrxmprk/public_html"
PLUGINS_PATH="${REMOTE_PATH}/wp-content/plugins"
MAIN_PLUGIN="hvac-community-events"

echo -e "${YELLOW}=== Cleaning Up HVAC Community Events Plugins ===${NC}"
echo -e "${YELLOW}Target: ${REMOTE_USER}@${REMOTE_HOST}:${PLUGINS_PATH}${NC}"

# Create a temporary script to perform the cleanup
TEMP_FILE=$(mktemp)
cat > "$TEMP_FILE" << 'EOPHP'
<?php
/**
 * HVAC Plugin Cleanup Script
 * 
 * This script identifies and lists all HVAC Community Events plugin variants
 * to assist with cleanup.
 */

// Configuration
$plugins_dir = __DIR__ . '/wp-content/plugins';
$main_plugin = 'hvac-community-events';

// Function to check if a directory is an HVAC plugin
function is_hvac_plugin($dir) {
    // Skip non-directories
    if (\!is_dir($dir)) {
        return false;
    }
    
    // Skip the main plugin we want to keep
    if (basename($dir) === 'hvac-community-events') {
        return false;
    }
    
    // Check if it's an HVAC plugin variant
    if (strpos(basename($dir), 'hvac') \!== false) {
        return true;
    }
    
    // Check plugin files for HVAC content
    $main_file = $dir . '/' . basename($dir) . '.php';
    if (file_exists($main_file)) {
        $content = file_get_contents($main_file);
        if (strpos($content, 'HVAC') \!== false || 
            strpos($content, 'hvac') \!== false ||
            strpos($content, 'community-events') \!== false) {
            return true;
        }
    }
    
    return false;
}

// Scan the plugins directory
$hvac_plugins = [];
$all_plugins = scandir($plugins_dir);
foreach ($all_plugins as $plugin) {
    if ($plugin === '.' || $plugin === '..') {
        continue;
    }
    
    $plugin_path = $plugins_dir . '/' . $plugin;
    if (is_hvac_plugin($plugin_path)) {
        $hvac_plugins[] = $plugin;
    }
}

// Output the list of plugins to remove
if (\!empty($hvac_plugins)) {
    echo "Found " . count($hvac_plugins) . " HVAC plugin variants to remove:\n";
    echo implode("\n", $hvac_plugins) . "\n";
    
    // Generate bash commands to remove the plugins
    echo "\n### REMOVAL COMMANDS ###\n";
    foreach ($hvac_plugins as $plugin) {
        echo "rm -rf " . escapeshellarg($plugins_dir . '/' . $plugin) . "\n";
    }
} else {
    echo "No HVAC plugin variants found. Only the main plugin '$main_plugin' exists.\n";
}
EOPHP

# Upload and run the identification script
echo -e "${YELLOW}Uploading and running identification script...${NC}"
sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no "$TEMP_FILE" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH/hvac-cleanup-identify.php"

if [ $? -ne 0 ]; then
    echo -e "${RED}Error: Failed to upload identification script. Aborting.${NC}"
    rm "$TEMP_FILE"
    exit 1
fi

# Run the identification script
echo -e "${YELLOW}Running identification script...${NC}"
REMOVAL_COMMANDS=$(sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "cd $REMOTE_PATH && php hvac-cleanup-identify.php")

if [ $? -ne 0 ]; then
    echo -e "${RED}Error: Failed to run identification script. Aborting.${NC}"
    sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "rm -f $REMOTE_PATH/hvac-cleanup-identify.php"
    rm "$TEMP_FILE"
    exit 1
fi

# Display identification results
echo -e "${YELLOW}Identification Results:${NC}"
echo "$REMOVAL_COMMANDS"

# Extract removal commands
COMMANDS=$(echo "$REMOVAL_COMMANDS" | awk '/### REMOVAL COMMANDS ###/{flag=1;next} flag')

if [ -z "$COMMANDS" ]; then
    echo -e "${GREEN}No plugins to remove. Skipping cleanup.${NC}"
else
    # Ask for confirmation
    echo -e "${YELLOW}The above plugins will be permanently removed.${NC}"
    read -p "Do you want to proceed with removal? (y/n): " CONFIRM
    
    if [ "$CONFIRM" = "y" ] || [ "$CONFIRM" = "Y" ]; then
        # Create a cleanup script
        CLEANUP_SCRIPT=$(mktemp)
        cat > "$CLEANUP_SCRIPT" << EOC
#\!/bin/bash
# Backup the main plugin first
echo "Creating backup of main HVAC Community Events plugin..."
timestamp=\$(date +%Y%m%d%H%M%S)
main_plugin_backup="$PLUGINS_PATH/hvac-backup-\$timestamp"
cp -r "$PLUGINS_PATH/hvac-community-events" "\$main_plugin_backup"
if [ \$? -eq 0 ]; then
    echo "Backup created at \$main_plugin_backup"
else
    echo "Warning: Failed to create backup. Continuing anyway."
fi

# Remove duplicate plugins
echo "Removing duplicate HVAC plugins..."
$COMMANDS

echo "Cleanup completed successfully."
EOC
        
        # Upload and run the cleanup script
        echo -e "${YELLOW}Uploading and running cleanup script...${NC}"
        sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no "$CLEANUP_SCRIPT" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH/hvac-cleanup-execute.sh"
        sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "cd $REMOTE_PATH && chmod +x hvac-cleanup-execute.sh && ./hvac-cleanup-execute.sh"
        
        if [ $? -eq 0 ]; then
            echo -e "${GREEN}Cleanup completed successfully.${NC}"
        else
            echo -e "${RED}Error: Cleanup failed.${NC}"
        fi
        
        # Remove cleanup scripts
        echo -e "${YELLOW}Removing cleanup scripts...${NC}"
        sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "rm -f $REMOTE_PATH/hvac-cleanup-execute.sh $REMOTE_PATH/hvac-cleanup-identify.php"
        
        rm "$CLEANUP_SCRIPT"
    else
        echo -e "${YELLOW}Cleanup cancelled by user.${NC}"
    fi
fi

# Clean up local temp file
rm "$TEMP_FILE"

# Check if main plugin exists
echo -e "${YELLOW}Checking if main plugin exists...${NC}"
MAIN_PLUGIN_EXISTS=$(sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "if [ -d \"$PLUGINS_PATH/$MAIN_PLUGIN\" ]; then echo 'yes'; else echo 'no'; fi")

if [ "$MAIN_PLUGIN_EXISTS" = "yes" ]; then
    echo -e "${GREEN}Main plugin 'hvac-community-events' exists. Proceed with Zoho fix deployment.${NC}"
else
    echo -e "${RED}Error: Main plugin 'hvac-community-events' does not exist. Please check the plugin directory.${NC}"
    exit 1
fi

echo -e "${GREEN}=== Plugin Cleanup Completed ===${NC}"
echo -e "${YELLOW}You can now deploy the Zoho fix.${NC}"

exit 0
