#!/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 domain you wish perform search and replace on..."
    echo
    ls /var/www | grep -v html | nl
    read -p "Select domain: " 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



if [[ -z $search_term ]]; then
    echo
    echo "What are you searching for?  
If you are searching for a domain, just enter the destination domain name without the www or http://.
Example: my-new-domain.com"
    read -p "Domain or search term: " search_term
fi

if [[ -z $replace_term ]]; then
    echo
    echo "What are you replacing this with?  
If you are searching for a domain, just enter the destination domain name without the www or http://.
Example: my-new-domain.com"
    read -p "New domain or replacement term: " replace_term
fi


#get the database name
mysql_db=$(grep DB_NAME /var/www/$domain/html/wp-config.php | cut -d "'" -f 4)
mysql_dbprefix=$(grep table_prefix /var/www/$domain/html/wp-config.php | cut -d "'" -f 2)


#backup database
echo "Backing up database..."
date=$(date +"%Y-%m-%d"-"%Hh%Mm%Ss")
mkdir -p ~/.wp-backup/$domain/
mysqldump $mysql_db | gzip -9 > ~/.wp-backup/$domain/"$domain"_"$date"_db.gz
if [ $? -ne 0 ]  
then
	echo "Database backup failed! Domain change aborted!"
	exit
fi
echo "Database backed up to ~/.wp-backup/$domain/"$domain"_"$date"_db.gz"

#run search and replace using wp-cli
echo "Starting search and replace..."
cd /var/www/$domain/html/
su - $domain -c "wp --skip-plugins search-replace $search_term $replace_term --recurse-objects --network --skip-columns=guid --skip-tables=wp_users --all-tables-with-prefix"
# reset cache
su - $domain -c "wp cache flush"
su - $domain -c "wp cache-enabler clear 2>/dev/null"



echo "Restarting NGINX..."
systemctl restart nginx

echo
echo "Search and replace complete.  We searched for $search_term and changed it to $replace_term"