#!/bin/sh
#
# ons control script designed to allow an easy command line interface
# to controlling ons daemon.
# 
#
# |||||||||||||||||||| START CONFIGURATION SECTION  ||||||||||||||||||||
# --------------------                              --------------------
#
ulimit -n 1024
#
ORACLE_HOME=%ORACLE_HOME%; export ORACLE_HOME
#
if [ -z "$ORACLE_HOME" ]
then
echo "ORACLE_HOME must be set in your environment to run onsctl"
exit 1
fi
NLS_LANG=${NLS_LANG="AMERICAN_AMERICA.WE8MSWIN1252"}; export NLS_LANG
#
#
if [ -z "$LD_LIBRARY_PATH" ]
then 
        LD_LIBRARY_PATH=$ORACLE_HOME/lib ; export LD_LIBRARY_PATH
else
        LD_LIBRARY_PATH=$ORACLE_HOME/lib:${LD_LIBRARY_PATH} ; export LD_LIBRARY_PATH
fi
#
ONS=$ORACLE_HOME/opmn/bin/ons
ONSADMIN="$ONS -a"

#
# ||||||||||||||||||||   END CONFIGURATION SECTION  ||||||||||||||||||||

detailed_usage()
{
echo "usage: $0 start|stop|ping|reconfig|debug"
cat <<EOF

start
    Start ons daemon

stop
    Shutdown ons daemon

reconfig
    Trigger ons to re-read it's configuration files.  

ping
    Test to see if ons daemon is alive

debug
    Display debug information about the ons daemon

help
    Print a short syntax description.

detailed
    Print a verbose syntax description (this message).

EOF
}

usage()
{
echo "usage: $0 start|stop|ping|reconfig|debug"
cat <<EOF

start                            - Start opmn only.
stop                             - Stop ons daemon
ping                             - Test to see if ons daemon is running
debug                            - Display debug information for the ons daemon
reconfig                         - Reload the ons configuration
help                             - Print a short syntax description (this).
detailed                         - Print a verbose syntax description.

EOF
}

ping_ons()
{
$ONSADMIN ping
if [ $? -ne 0 ]
then
  echo "ons is not running ..."
  exit 1
else
  echo "ons is running ..."
  exit 0
fi
}

start_ons()
{
$ONSADMIN ping
EXIT=$?
if [ $EXIT -eq 0 ]
then
  echo "onsctl: ons is already running"
  exit 1
fi

$ONS -d

sleep 1
$ONSADMIN pingwait
EXIT=$?
if [ $EXIT -ne 0 ]
then
  echo "onsctl: ons failed to start"
  exit 1
else
  echo "onsctl: ons started"
fi
} 

stop_ons()
{
$ONSADMIN shutdown
EXIT=$?
if [ $EXIT -ne 0 ]
then
  echo "onsctl: shutdown of ons failed!"
fi
} 

debug_ons()
{
$ONSADMIN debug
} 


if [ $# -eq 0 ] ; then 
    set help
fi

EXIT=0
CMDARG=$1
shift
case $CMDARG in
    start)
        if [ $# -gt 0 ] ; then
            usage
            EXIT=1
        else
            start_ons TRUE
        fi
        ;;
    stop)
        echo "onsctl: shutting down ons daemon ..."
        stop_ons 
        ;;
    ping)
        ping_ons
        ;;
    debug)
        debug_ons
        ;;
    reconfig)
        ;;
    detailed)
        detailed_usage
        ;;
    help)
        usage
        ;;
    *)
        usage
        EXIT=1
        ;;
esac

exit $EXIT
