#!/bin/bash
DIR2UPDATE=$1
NAME=$2
VERSION=$3

echo "Beginning update of $DIR2UPDATE to version $VERSION..."

if [ -d wordpress_svn ]
then
	day=`date | cut -d" " -f3`
	tme=`date | cut -d" " -f4`
	hour=`echo ${tme} | cut -d":" -f1`

	fileday=`ls -lh | grep wordpress_svn | cut -c 37-39`
	filehour=`ls -lh | grep wordpress_svn | cut -c 40-41`

	if [ ${fileday} != ${day} ]; then
        	echo "SVN directory not up to date, [ file's date ${fileday} != today ${day} ] deleting and updating"
		rm -rf wordpress_svn/*
		cd wordpress_svn
        	svn co http://svn.automattic.com/wordpress/tags/${VERSION} .
	else
        	if [ "$filehour" != "$hour" ]; then
                	echo "SVN directory not up to date, [ file's hour ${filehour} != now ${hour} ] deleting and updating"
        		rm -rf wordpress_svn/*
                	cd wordpress_svn
                	svn co http://svn.automattic.com/wordpress/tags/${VERSION} .
		else
                	echo "SVN directory is up to date, skipping update"
        		cd wordpress_svn
		fi
	fi

else
	echo "Creating new svn directory and checking out version $VERSION...";
	mkdir wordpress_svn;
	cd wordpress_svn;
	svn co http://svn.automattic.com/wordpress/tags/${VERSION} .;
fi

cd ..

if [ -d wordpress_int ]
then
	echo "Removing old intermediate container...";
	rm -rf wordpress_int;
fi

echo "Creating new intermediate container..."
mkdir wordpress_int
echo "Moving version $VERSION files into intermediate container..."
cp -rpf wordpress_svn/* wordpress_int

echo "Moving config and custom files from $NAME into intermediate container..."

cp -p ${DIR2UPDATE}/wp-config.php wordpress_int
cp -rpf ${DIR2UPDATE}/wp-content/* wordpress_int/wp-content/
cp -p ${DIR2UPDATE}/.htaccess wordpress_int
echo 'Updating svn for wp-content'
svn update wordpress_int

echo "Backing up $DIR2UPDATE..."
mkdir ${NAME}_backup
#mv -f ${DIR2UPDATE}/* ${NAME}_backup	# if you'd like to mv instead of cp
cp -rpf ${DIR2UPDATE}/* ${NAME}_backup
tar -czvf ${NAME}_backup.tar.gz ${NAME}_backup
rm -rf ${NAME}_backup

echo 'Removing svn data from intermediate container...' 
rm -rf `find wordpress_int/ -type d -name .svn`
echo "Moving intermediate container contents to $DIR2UPDATE..."
cp -rpf wordpress_int/* ${DIR2UPDATE}


