#!/bin/bash
if [[ "$EUID" -ne 0 ]]; then
	echo "Sorry, you need to run this as root"
	exit
fi



while [[ -z $domain ]]; do
    clear
    echo "Please, select which site you want to work with"
    ls /var/www | grep -v html | nl
    echo
    read -p "Select site: " site_number
    number_of_sites=$(ls /var/www | grep -v html | wc -l)
    until [[ "$site_number" =~ ^[0-9]+$ && "$site_number" -le "$number_of_sites" ]]; do
    	echo "$site_number: invalid selection."
    	read -p "Select site: " site_number
    done
    domain=$(ls /var/www | grep -v html | sed -n "$site_number"p)
done



while [[ -z $action ]]; do
    clear
    echo "What do you want to do?"
    echo "   1) Enable WordPress Cache"
    echo "   2) Disable WordPress Cache"
    echo "   3) Clear WordPress Cache"
    echo
    read -p "Action: " action
    until [[ -z "$action" || "$action" =~ ^[1-3]$ ]]; do
    	echo "$action: invalid selection."
    	read -p "Action: " action
    done
done



user_name=$(echo $domain | cut -c1-32)



cd /var/www/$domain/html/



if [[ $action == "enable_page_cache" || $action == "1" ]]; then

    su - $user_name -c "wp  plugin install --activate cache-enabler"
	su - $user_name -c "wp --skip-plugins config set WP_CACHE true"

    echo
    echo "WordPress Cache has been enabled for $domain"
    exit
fi


if [[ $action == "disable_page_cache" || $action == "2" ]]; then

    su - $user_name -c "wp plugin deactivate cache-enabler"
    su - $user_name -c "wp plugin uninstall cache-enabler"
	su - $user_name -c "wp --skip-plugins config set WP_CACHE false"

    echo
    echo "WordPress Cache has been disabled for $domain"
    exit
fi


if [[ $action == "clear_page_cache" || $action == "3" ]]; then

    su - $user_name -c "wp cache-enabler clear"

    echo
    echo "WordPress Cache has been cleared for $domain"
    exit
fi
