Friday, March 22, 2013

Development deploy script for Wordpress

If your working on many different WordPress sites with other people the process of keeping your local database in sync with whats happening in the repository starts to get tedious. To alleviate some of the hassle, I've created a simple bash script that works with a properties file to drop and recreate a WordPress database. The idea is, you put the script on path, and the specific properties of the WordPress install in your repository.  Then you can easy run the script to refresh the database for you once you pull in fresh changes. Here is an example of the deploy.properties file.

DATABASE_SCRIPT=test_database.sql
DATABASE_NAME=mysite
DATABASE_USERNAME=test_user
DATABASE_PASSWORD=test_pass
HOST_URL=http://localhost/mysite/


Once you have this file setup properly, running the script will drop, recreate and update the site url and home properties in the database. The script is as follows.

#!/bin/bash

SETTINGS_FILE=deploy.properties

if [ -f $SETTINGS_FILE ];
then

 # Include settings file
 . "$PWD/$SETTINGS_FILE"

 echo "Dropping old database (if it exists)"
 mysql -u$DATABASE_USERNAME -p$DATABASE_PASSWORD -e "DROP DATABASE IF EXISTS $DATABASE_NAME";

 echo "Recreating database"
 mysql -u$DATABASE_USERNAME -p$DATABASE_PASSWORD -e "CREATE DATABASE $DATABASE_NAME";

 if [ -f $DATABASE_SCRIPT ];
 then
    echo "Running database script"
    mysql -u$DATABASE_USERNAME -p$DATABASE_PASSWORD $DATABASE_NAME < $DATABASE_SCRIPT
    
    echo "Updating wordpress settings."

    mysql -u$DATABASE_USERNAME -p$DATABASE_PASSWORD $DATABASE_NAME -e "update wp_options set option_value=\"$HOST_URL\" where option_name=\"siteurl\""
    mysql -u$DATABASE_USERNAME -p$DATABASE_PASSWORD $DATABASE_NAME -e "update wp_options set option_value=\"$HOST_URL\" where option_name=\"home\""

 else
    echo "Database script does not exist. Aborting."
 fi
else
 echo "Cannot find settings file $SETTINGS_FILE in current directory."
fi