#!/bin/bash

# Deploy HVAC Community Events plugin via WP-CLI
# This script uses SSH to execute WP-CLI commands on the remote server
# It handles plugin installation, activation, and verification

# Get absolute path to this script's directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Navigate to wordpress-dev directory
cd "$(dirname "$SCRIPT_DIR")" || exit 1

# Load environment variables
ENV_FILE=".env"
if [ ! -f "$ENV_FILE" ]; then
    echo "Error: .env file not found at: $ENV_FILE"
    exit 1
fi

source "$ENV_FILE"

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

# Function to check if a command was successful
check_status() {
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ $1${NC}"
        return 0
    else
        echo -e "${RED}✗ $1${NC}"
        return 1
    fi
}

# Function to run WP-CLI commands remotely
remote_wp_cli() {
    COMMAND="$1"
    sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" "cd ${UPSKILL_STAGING_PATH} && wp $COMMAND --allow-root"
}

echo "=== Deploying HVAC Community Events Plugin via CLI ==="
echo "Remote host: ${UPSKILL_STAGING_IP} (upskill-staging.measurequick.com)"
echo "Remote user: ${UPSKILL_STAGING_SSH_USER}"
echo "WordPress path: ${UPSKILL_STAGING_PATH}"
echo "Plugin package: plugin-backups/hvac-community-events.zip"
echo "======================================================="

# Step 1: Check if plugin exists and deactivate it if it does
echo -e "\n${YELLOW}Checking if plugin is already installed...${NC}"
PLUGIN_STATUS=$(remote_wp_cli "plugin get hvac-community-events --field=status" 2>/dev/null)

if [ $? -eq 0 ]; then
    echo -e "${YELLOW}Plugin is already installed with status: $PLUGIN_STATUS${NC}"
    
    # Deactivate plugin if active
    if [ "$PLUGIN_STATUS" = "active" ]; then
        echo -e "${YELLOW}Deactivating existing plugin...${NC}"
        remote_wp_cli "plugin deactivate hvac-community-events"
        check_status "Plugin deactivated"
    fi
    
    # Make backup of existing plugin
    echo -e "${YELLOW}Creating backup of existing plugin...${NC}"
    BACKUP_DATE=$(date +%Y%m%d%H%M%S)
    remote_wp_cli "plugin get hvac-community-events --field=path" | xargs -I {} sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" "cp -r {} {}.bak.$BACKUP_DATE"
    check_status "Plugin backup created"
    
    # Delete existing plugin
    echo -e "${YELLOW}Removing existing plugin...${NC}"
    remote_wp_cli "plugin delete hvac-community-events"
    check_status "Existing plugin deleted"
else
    echo -e "${YELLOW}Plugin not currently installed.${NC}"
fi

# Step 2: Upload plugin zip file
echo -e "\n${YELLOW}Uploading plugin package...${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" scp "plugin-backups/hvac-community-events.zip" "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}:${UPSKILL_STAGING_PATH}"
check_status "Plugin package uploaded"

# Step 3: Install plugin
echo -e "\n${YELLOW}Installing plugin...${NC}"
remote_wp_cli "plugin install ${UPSKILL_STAGING_PATH}/hvac-community-events.zip --force"
check_status "Plugin installed"

# Step 4: Activate plugin
echo -e "\n${YELLOW}Activating plugin...${NC}"
remote_wp_cli "plugin activate hvac-community-events"
check_status "Plugin activated"

# Step 5: Clean up
echo -e "\n${YELLOW}Cleaning up...${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" "rm -f ${UPSKILL_STAGING_PATH}/hvac-community-events.zip"
check_status "Temporary files removed"

# Step 6: Verify installation
echo -e "\n${YELLOW}Verifying installation...${NC}"
PLUGIN_VERSION=$(remote_wp_cli "plugin get hvac-community-events --field=version")
check_status "Plugin installed with version: $PLUGIN_VERSION"

# Check if plugin roles are created
echo -e "\n${YELLOW}Checking plugin roles...${NC}"
ROLES=$(remote_wp_cli "role list --field=role")
if [[ $ROLES == *"hvac_trainer"* ]]; then
    echo -e "${GREEN}✓ HVAC Trainer role exists${NC}"
else
    echo -e "${RED}✗ HVAC Trainer role not found${NC}"
fi

# Step 7: Flush rewrite rules
echo -e "\n${YELLOW}Flushing rewrite rules...${NC}"
remote_wp_cli "rewrite flush --hard"
check_status "Rewrite rules flushed"

echo -e "\n${GREEN}Plugin deployment completed!${NC}"
echo "Plugin: hvac-community-events"
echo "Version: $PLUGIN_VERSION"
echo "Status: $(remote_wp_cli "plugin get hvac-community-events --field=status")"
echo -e "\nNext steps:"
echo "1. Set up test users with './bin/setup-staging-test-users.sh'"
echo "2. Create test data with './bin/create-comprehensive-test-data.sh'"
echo "3. Verify Zoho CRM integration with the verification guide"