#!/bin/bash
# Daemon for the NetApp Virtual Storage Console for Red Hat Enterprise
# Virtualization
# chkconfig: 345 20 80
# description: Daemon for the NetApp Virtual Storage Console for Red Hat Enterprise Virtualization
# processname: vsc

#
# $Id: //depot/prod/mobius/RAce.1/conf/vsc#1 $
# 
# Copyright (c) 2013 NetApp, Inc.
# All rights reserved
#

VSC_HOME=/usr/local/vsc
VSC_LOG_DIR=/var/log/vsc
VSC_LOG=$VSC_LOG_DIR/jetty_out.log
VSC_CMD="java -Xmx2048m -Xms256m -jar $VSC_HOME/jetty-runner.jar --config $VSC_HOME/jetty.xml $VSC_HOME/vsc-rhev.war"
PID_FILE=/var/lock/subsys/vsc

# Source the functions library
#. /etc/init.d/functions

# Starts the VSC service
start() {
    # Check if the pid file exists
    if [ -f $PID_FILE ]; then 
        PID=`cat $PID_FILE`
        if [ -z "`ps aux | grep ${PID} | grep -v grep`" ]; then
            # VSC service is dead, but the pid file exists. Remove it and start
            # the service fresh.
            rm -f $PID_FILE
        else 
            echo "VSC for RHEV service has already been started."
            exit 1
        fi 
    fi

    # Check to see if the vsc log directory exists
    if [ ! -d $VSC_LOG_DIR ]; then
        mkdir -p $VSC_LOG_DIR
    fi

    # Start the service
    echo -n "Starting VSC for RHEV service..."
    $VSC_CMD &> $VSC_LOG &
    VSC_PID=$!
    echo $VSC_PID > $PID_FILE
    echo "    OK"
}

stop() {
    # Check if the pid file exists
    if [ -f $PID_FILE ]; then
        echo -n "Stopping the VSC for RHEV service..."
        kill -HUP `cat $PID_FILE`
        rm -f $PID_FILE
        echo "    OK"
    else
        echo "VSC for RHEV service is not running."
        exit 1
    fi
}

status() {
    if [ -f $PID_FILE ]; then
        PID=`cat $PID_FILE`
        if [ -z "`ps aux | grep ${PID} | grep -v grep`" ]; then
            echo "VSC for RHEV service is not running"
        else
            echo "VSC for RHEV service is running"
        fi
    else
        echo "VSC for RHEV service is not running"
    fi
}

checkUser() {
    if [ ! $(id -u) = 0 ]; then 
        echo "You need to be root to run this command."
        exit 1
    fi
}

# Script must be run as root, so check that first
#if [ ! $(id -u) = 0 ]; then 
#    echo "You need to be root to run this script."
#    exit 1
#fi

case "$1" in 
    start)
        checkUser
        start
        ;;
    stop)
        checkUser
        stop
        ;;
    restart)
        checkUser
        if [ -e $PID_FILE ]; then
            stop
            sleep 3
        fi
        start
        ;;
    status)
        status
        ;;
    *)
        echo "Usage: $0 {status|start|stop|restart}"
        exit 1
esac

