Thursday, May 7, 2009

Bash Script to Redeploy war, Modify a File, Clear Logs, and Restart Tomcat

A bash script to redeploy a war, modify a file, clear logs, and restart tomcat.
#!/bin/bash
# go.sh
#
# Written by Gary S. Weaver
#
# Redeploy WAR, Modify a File, Clear Logs, and Restart Tomcat. Capistrano is also
# good at this stuff, but I just hacked this up as a bash script.

set -e

webapp="myapp"

if [ -z "$MYAPP_TOMCAT_HOME" ]; then
  echo
  echo "Must set MYAPP_TOMCAT_HOME environment variable to the MYAPP Tomcat home. for example: /mystuff/apache-tomcat-6.0.18"
  exit
fi

if [ ! -d "$MYAPP_TOMCAT_HOME" ]; then
  echo
  echo "Please update MYAPP_TOMCAT_HOME env variable with the location of tomcat"
  exit
fi

# Here we call the build. In our case it is warble, a rake wrapper.
warble

echo "removing ${MYAPP_TOMCAT_HOME}/webapps/${webapp}.war"
rm "${MYAPP_TOMCAT_HOME}/webapps/${webapp}.war"
if [ -f "$MYAPP_TOMCAT_HOME" ]; then
  echo
  echo "Couldn't delete ${MYAPP_TOMCAT_HOME}/webapps/${webapp}.war! Check your permissions/user."
  exit
fi

# loop to wait on webapp to undeploy
echo "Checking for ${MYAPP_TOMCAT_HOME}/webapps/${webapp}"
for (( c=1; c<=15; c++ ))
do
  if [ -d "${MYAPP_TOMCAT_HOME}/webapps/${webapp}" ]; then
    sleep 1
  fi
done

# We're assuming that the war is in the same directory. You may want to change that.
echo "copying ${webapp}.war to ${MYAPP_TOMCAT_HOME}/webapps/"
cp "${webapp}.war" "${MYAPP_TOMCAT_HOME}/webapps/"

# loop to wait on webapp to deploy
for (( c=1; c<=15; c++ ))
do
  if [ ! -d "${MYAPP_TOMCAT_HOME}/webapps/${webapp}" ]; then
    sleep 1
  fi
done

# hack to modify a file. in this case, we have a bug where we currently need to modify sinatra.rb
echo "Fixing sinatra.rb"
sinatrarb="${MYAPP_TOMCAT_HOME}/webapps/${webapp}/WEB-INF/gems/gems/sinatra-0.9.1.1/lib/sinatra.rb"
sed 's/use_in_file_templates/\#use_in_file_templates/g' "${sinatrarb}" > "${sinatrarb}.tmp" && mv "${sinatrarb}.tmp" "${sinatrarb}"

cd "${MYAPP_TOMCAT_HOME}/bin/"
echo "shutting down tomcat"
./shutdown.sh
sleep 3
echo "deleting old log files"
rm "${MYAPP_TOMCAT_HOME}/logs/*out*"
rm "${MYAPP_TOMCAT_HOME}/logs/*log*"

echo "starting up tomcat"
./startup.sh