#!/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
}

print_success_end_exit(){
    print_success
    exit 0
}

print_failure_and_exit(){
    print_failure
    exit 1
}

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

kill_process(){
    if [ ! -z $1 ]; then
        result=`kill $1`
        if [ $? -eq 0 ]; then
            print_success_end_exit
        else
            print_failure_and_exit
        fi
    fi
}

start(){
    echo "Starting OnApp Licensing Process ... "
    pid1=`find_pid "$APP_NAME"`
    pid2=`find_pid "$APP_STARTER"`
    if [[ ( -z ${pid1} ) && ( -z ${pid2} ) ]]; then
        su onapp -m -c "cd ${APP_PATH} && RAILS_ENV=${RAILS_ENV} rake ${APP_STARTER} >/dev/null 2>&1 &"
        sleep 2
        new_pid=`find_pid "$APP_STARTER"`
        echo -e "Done. Process name: onapp_licensing. PID: ${new_pid}"
        print_success_end_exit
    elif [[ ( -z ${pid1} ) && ( ! -z ${pid2} ) ]]; then
        echo -e "Another instance of OnApp Licensing process is warming up... PID: ${pid2}"
        print_failure_and_exit
    else
        echo -e "Another instance of OnApp Licensing process is already running. PID: ${pid1}"
        print_failure_and_exit
    fi
}

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

    pid1=`find_pid "$APP_NAME"`
    pid2=`find_pid "$APP_STARTER"`
    if [[ ( -z ${pid1} ) && ( -z ${pid2} ) ]]; then
       echo "There is no active OnApp Licensing Process "
    fi

    if [ ! -z ${pid1} ]; then
        kill_process ${pid1}
    fi

    if [ ! -z ${pid2} ]; then
        kill_process ${pid2}
    fi

    for pid in ${pid1} ${pid2}; do
        while kill -0 "$pid" 2> /dev/null; do
            sleep 0.5
        done
    done
}

restart(){
    stop
    sleep 2
    start
}

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

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