#!/bin/bash
#
# onapp         This script manages OnApp Licensing Client
#
# chkconfig:    - 80 20
# description:  OnApp Licensing Client

# Source onapp functions
. /onapp/interface/script/init/onapp_functions.sh

APP_PATH=/onapp/interface
APP_STARTER=onapp:licensing:start
APP_NAME=onapp_licensing

usage(){
    generic_usage
}

find_pid(){
    ps ax | grep $1 | grep -v "grep\|bash" | awk '{ print $1 }'
}

wait_pid(){
    local COUNT
    local MAXCOUNT
    local SLEEP
    local WAIT_PID
    MAXCOUNT=40
    COUNT=0
    SLEEP=1
    WAIT_PID=$1

    while kill -s 0 $WAIT_PID >/dev/null 2>&1 ; do
        COUNT=$(($COUNT + 1))
        if [ $COUNT -gt $MAXCOUNT ] ; then
          return 1
        fi
        sleep $SLEEP
    done

    return 0
}

start(){
    echo -n "Starting OnApp Licensing Process ... "
    pid1=`find_pid "$APP_NAME"`
    pid2=`find_pid "$APP_STARTER"`
    if [[ ( -z ${pid1} ) && ( -z ${pid2} ) ]]; then
        CURRENTDIR=$(pwd)
        cd ${APP_PATH} && su onapp -m -c "RAILS_ENV=${RAILS_ENV} rake ${APP_STARTER} >/dev/null 2>&1 &"
        cd ${CURRENTDIR}
        print_success
        return 0
    elif [[ ( -z ${pid1} ) && ( ! -z ${pid2} ) ]]; then
        echo -e "\nAnother instance of OnApp Licensing process is warming up... PID: ${pid2}"
        print_failure
        return 1
    else
        echo -e "\nAnother instance of OnApp Licensing process is already running. PID: ${pid1}"
        print_failure
        return 1
    fi
}

stop(){
    echo -n "Stopping OnApp Licensing Process ... "

    for APP in "${APP_STARTER}" "${APP_NAME}" ; do 
        APP_PID=$(find_pid "${APP}")
        if [ ! -z ${APP_PID} ]; then
            kill ${APP_PID}
            wait_pid ${APP_PID}
            if [ $? -ne 0 ]; then 
                kill -s SIGKILL ${APP_PID} >/dev/null 2>&1
                wait_pid ${APP_PID}
            fi
        fi
    done

    if [ $? -eq 0 ]; then 
        print_success
        return 0
    else
        print_failure
        return 1
    fi
}

restart(){
    stop
    start
}

status(){
    pid1=`find_pid "$APP_NAME"`
    pid2=`find_pid "$APP_STARTER"`
    if [ ! -z ${pid1} ]; then
        echo "OnApp Licensing Process is active. PID: ${pid1}"
        return 0
    elif [[ ( -z ${pid1} ) && ( ! -z ${pid2} ) ]]; then
        echo "OnApp Licensing Process is warming up. PID: ${pid2}"
        return 0
    else
        echo "There is no active OnApp Licensing Process "
        return 3
    fi
}

case "$1" in
  status)
        status
        ;;
  start)
        start
        ;;
  stop)
        stop
        ;;
  restart)
        restart
        ;;
  *)
        usage
        ;;
esac
