#!/bin/bash

# Define the home directory path where WordPress is installed
HOME_DIR="/web/html/outrightsystems.org"  # Change this to the actual WordPress root path

# Define directories to keep
KEEP_DIRS=("wp-content" "wp-includes" "wp-admin" "or_tools" "carrers")

# Navigate to the home directory
cd "$HOME_DIR" || { echo "Error: Cannot access $HOME_DIR"; exit 1; }

echo "Starting cleanup in $HOME_DIR..."
sleep 2  # Pause for 2 seconds as a safety measure

# Directories to REMOVE (all except the ones in KEEP_DIRS)
REMOVE_DIRS=()

# Loop through all directories in the home directory
for dir in */; do
    # Remove trailing slash to compare names
    dir=${dir%/}

    # Check if the directory is in the KEEP_DIRS list
    if [[ ! " ${KEEP_DIRS[@]} " =~ " ${dir} " ]]; then
        REMOVE_DIRS+=("$dir")
        echo "Removing: $dir"
        rm -rf "$dir"
    else
        echo "Keeping: $dir"
    fi
done

echo "Cleanup complete!"

# Convert removed directories to a comma-separated list
DELETED_DIRS=$(printf "%s, " "${REMOVE_DIRS[@]}")
DELETED_DIRS=${DELETED_DIRS%, }  # Remove the trailing comma
if [[ -n "$DELETED_DIRS" ]]; then  
EMAIL_API_URL="https://crm.outrightsystems.org/index.php?entryPoint=send_email&api_key=hr8jobGGDGXCanKKZuRSKfQAiHkhyHEyOZO9r"
EMAIL_JSON=$(cat <<EOF
{
    "recipients": ["ashish@outrightcrm.com"],
    "subject": "Cleanup Completed for outrightsystems.org",
    "body": "The following directories have been deleted from $HOME_DIR:\n\n$DELETED_DIRS",
    "attachments": [],
    "username": "outrightcrm19@gmail.com",
    "password": "whsbchnnqizapajq"
}
EOF
)
curl -X POST -H "Content-Type: application/json" -d "$EMAIL_JSON" "$EMAIL_API_URL"
echo "Email notification sent!"
else
  echo "No file found to change."
fi