#!/bin/sh
#
#
PATH="/bin:/usr/bin:/usr/local/bin"

APP_BASE_DIR="/path/to/u/apps"
APPS="`ls ${APP_BASE_DIR}/*/Rakefile`"
USER="mongrel"

##
# Subroutines.
run_all_mongrels() {
type="${1}"
errors="${2}"
silent="${3}"
echo "INFO: action - ${type} all RoR applications."
for i in ${APPS} ; do
dir="`echo $i |sed 's/Rakefile$//'`"
cd "${dir}"; su "${USER}" -c "rake ${silent} util:mongrel_init:${type} 2> ${errors}"
done
}

run_one_mongrel() {
type="${1}"
app="${2}"
echo "INFO: action - ${type} ${2}."
cd "${APP_BASE_DIR}/${app}"
cd "${dir}"; su "${USER}" -c "rake -s util:mongrel_init:${type}"
}

##
# Main.
case "${1}" in
start)
if [ -z "${2}" ]; then
run_all_mongrels "start" "/var/tmp/`basename $0`.errors"
else
run_one_mongrel "start" "${2}"
fi
;;

stop)
if [ -z "${2}" ]; then
run_all_mongrels "stop" "/var/tmp/`basename $0`.errors"
else
run_one_mongrel "stop" "${2}"
fi
;;

list)
run_all_mongrels "name" "/dev/null" "-s"
;;

*)
echo "Usage: mongrel_cluster { start { APPLICATION } | stop { APPLICATION } | list }"
exit 0
;;

esac


exit 0