#!/bin/sh
usage="$0 [-pu] [-t theme] wordpress-dir backup-dir"
theme=""
skipuploads=""
skipplugins=""

while getopts put: o
do	case "$o" in
	t)	theme="$OPTARG";;
	u)	skipuploads="1";;
	p)	skipplugins="1";;
	[?])	echo $usage
		exit 1;;
	esac
done
SHIFT=`echo $OPTIND - 1 | bc`
shift $SHIFT

wordpress=$1
backup=$2
if [ "$wordpress" = "" ]; then
	echo $usage;
	exit 1;
fi
if [ "$backup" = "" ]; then
	echo $usage;
	exit 1;
fi

command="rsync -avz"
date=`date "+%Y-%m-%d"`


#wordpress files
content="$wordpress/wp-content"
uploads="$content/uploads"
themes="$content/themes"
plugins="$content/plugins"
config="$wordpress/wp-config.php"

echo "Reading Database Params"
cd $wordpress
dbname=`sed -n "s/^define.'DB_NAME'.*'\(.*\)'.*$/\1/p" wp-config.php`
dbuser=`sed -n "s/^define.'DB_USER'.*'\(.*\)'.*$/\1/p" wp-config.php`
dbpassword=`sed -n "s/^define.'DB_PASSWORD'.*'\(.*\)'.*$/\1/p" wp-config.php`
dbhost=`sed -n "s/^define.'DB_HOST'.*'\(.*\)'.*$/\1/p" wp-config.php`

echo "Creating Database Backup"
mysqldump -h $dbhost -u $dbuser -p$dbpassword $dbname | gzip > $backup/wordpress.sql.gz;

if [ "$skipuploads" = "" ]; then
	echo "Backing Up Uploads"
	$command "$uploads" "$backup"
fi

if [ "$skipplugins" = "" ]; then
	echo "Backing Up Plugins"
	$command "$plugins" "$backup"
fi

if [ "$theme" = "" ]; then
	echo "Backing Up All Themes"
	$command "$themes" "$backup"
elif [ "$theme" != "-1" ]; then
	echo "Backing Up Single Theme"
	if [ -d "$backup/themes" ]; then
		#No need to create directory
		echo
	else
		mkdir "$backup/themes"
	fi
	$command "$themes/$theme" "$backup/themes"
fi
