#!/bin/bash

wait_for_jabberd() {
    RETRIES=10
    while [ $RETRIES -gt 0 ]
    do
        /usr/sbin/lsof -t -i :5222 > /dev/null && break
        ((RETRIES-1))
        sleep 0.5
    done
}

wait_for_tomcat() {
if [ -x /etc/init.d/tomcat5 ]; then
   TOMCAT="tomcat5"
elif [ -x /etc/init.d/tomcat6 ]; then
   TOMCAT="tomcat6"
elif [ -e /lib/systemd/system/tomcat.service ]; then
   TOMCAT="tomcat"
else
   echo "No tomcat service found."
   exit 0;
fi

if [ -x /usr/sbin/lsof ]; then
    echo "Waiting for tomcat to be ready ..."
    TOMCAT_PID=$(cat /var/run/$TOMCAT.pid 2>/dev/null)
    while [ -n "$TOMCAT_PID" ] ; do
        /usr/sbin/lsof -t -i TCP:8005 | grep "^$TOMCAT_PID$" > /dev/null \
        && /usr/sbin/lsof -t -i TCP:8009 | grep "^$TOMCAT_PID$" > /dev/null \
        && break
        sleep 1
    done
else
    echo "No lsof found, not waiting for tomcat."
fi
}

ensure_httpd_down() {
    COUNT=0
    LIMIT=10

    while [ "$(pidof httpd | wc -w)" -gt 0 ] && [ "$COUNT" -lt "$LIMIT" ]
    do
       sleep 1
       ((COUNT++))
    done

    if [ "$COUNT" -eq "$LIMIT" ]; then
       killall -9 httpd
       sleep 4
    fi

    return 0
}

case $1 in
        ensure-httpd-down) ensure_httpd_down;;
        wait-for-jabberd) wait_for_jabberd;;
        wait-for-tomcat) wait_for_tomcat;;
esac
