#!/bin/bash

# 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'

echo -e "${YELLOW}=== Clearing Breeze Cache on Staging Server ===${NC}"
echo "Remote host: $UPSKILL_STAGING_IP"
echo "Remote user: $UPSKILL_STAGING_SSH_USER"
echo "WordPress path: $UPSKILL_STAGING_PATH"
echo "==============================="

# Method 1: Try to clear Breeze cache using direct file system approach
echo -e "\n${YELLOW}Clearing Breeze cache files...${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" \
"cd ${UPSKILL_STAGING_PATH} && find wp-content/cache/breeze -type f -name '*.php' -delete 2>/dev/null"

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Breeze cache files cleared${NC}"
else
    echo -e "${YELLOW}Note: No Breeze cache files found or clearing failed${NC}"
fi

# Method 2: Clear Breeze minified files
echo -e "\n${YELLOW}Clearing Breeze minified files...${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" \
"cd ${UPSKILL_STAGING_PATH} && rm -rf wp-content/uploads/breeze/js/* wp-content/uploads/breeze/css/* 2>/dev/null"

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Breeze minified files cleared${NC}"
else
    echo -e "${YELLOW}Note: No minified files found${NC}"
fi

# Method 3: Try using WordPress transient API
echo -e "\n${YELLOW}Clearing Breeze-related transients...${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" \
"cd ${UPSKILL_STAGING_PATH} && wp transient delete '_breeze_minification' --allow-root 2>/dev/null"

# Also clear object cache if exists
echo -e "\n${YELLOW}Clearing object cache...${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" \
"cd ${UPSKILL_STAGING_PATH} && wp cache flush --allow-root"

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Object cache cleared${NC}"
else
    echo -e "${YELLOW}Note: Object cache clearing failed (might not be enabled)${NC}"
fi

# Clear transients
echo -e "\n${YELLOW}Clearing transients...${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" \
"cd ${UPSKILL_STAGING_PATH} && wp transient delete --all --allow-root"

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Transients cleared${NC}"
else
    echo -e "${YELLOW}Note: Transient clearing failed${NC}"
fi

echo -e "\n${GREEN}Cache clearing completed!${NC}"