#!/usr/bin/env bash
#
# zenoss        This shell script takes care of starting and stopping zenmon.
#               
# chkconfig: 2345 80 30
# description: Zenoss is a monitoring program written by Zenoss, Inc.
# 


#############################################################################
# This program is part of Zenoss Core, an open source monitoring platform.
# Copyright (C) 2007, Zenoss Inc.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as published by
# the Free Software Foundation.
#
# For complete information please visit: http://www.zenoss.com/oss/
#############################################################################
# Attempt to set ZENHOME if it is not already set, or bogus
# by calculating it relative to the executing command
if [ -z "$ZENHOME" -o ! -d "$ZENHOME" ] ; then
    # Resolve links: $0 may be a link to zenoss's home.
    PRG="$0"
    while [ -h "$PRG" ] ; do
        ls=`ls -ld "$PRG"`
        link=`expr "$ls" : '.*-> \(.*\)$'`
        if expr "$link" : '/.*' > /dev/null; then
            PRG="$link"
        else
            PRG=`dirname "$PRG"`"/$link"
        fi
    done
    SAVED="`pwd`"
    cd "`dirname \"$PRG\"`/.."
    ZENHOME="`pwd -P`"
    export ZENHOME
    cd "$SAVED"
fi

if [ `id -u` -eq 0 ] ; then
   USERNAME=`ls -l $ZENHOME/var/Data.fs | awk '{ print $3 }'`
   if [ "$USERNAME" = "root" -o -z "$USERNAME" ]  ; then 
       echo Unable to determine the right user to run zenoss
       exit 1
   fi
   chown -R $USERNAME $ZENHOME/var
   chown -R $USERNAME $ZENHOME/log
   exec su - $USERNAME $0 $@
fi

. $ZENHOME/bin/zenfunctions
C=
C="$C zeoctl"
C="$C zopectl"
C="$C zenhub"
C="$C zenping"
C="$C zensyslog"
C="$C zenstatus"
C="$C zenactions"
C="$C zentrap"
C="$C zenmodeler"
#C="$C zenrender"
C="$C zenperfsnmp"
C="$C zencommand"
C="$C zenprocess"
#C="$C zenmail"
if [ -f $ZENHOME/lib/python/pywmi.py ]
then
    C="$C zenwin"
    C="$C zeneventlog"
    C="$C zenwinmodeler"
fi
for i in $ZENHOME/Products/*/daemons/*
do
   if [ -x "$i" ]
   then
      C="$C `basename $i`"
   fi
done
CMDS=$C

reverse() {
    args=
    for i
    do
       args="$i $args"
       shift
    done
    echo $args
}

FUNC=$CMD

issue() {
    for cmd in $CMDS
    do
        echo -n "Daemon: $cmd "
        $ZENHOME/bin/$cmd "$FUNC"
    done
}

case "$FUNC" in
  start)
        issue
        ;;
  stop)
        CMDS=`reverse $CMDS`
        issue
        ;;
  restart)
        CMDS=`reverse $CMDS`
	FUNC=stop
	issue
        CMDS=`reverse $CMDS`
	FUNC=start
        issue
        ;;
  status)
        issue
        ;;
  list)
	for i in $CMDS
	do
	    echo $i
	done
	;;
  *)
        echo $"Usage: $0 {start|stop|restart|status|list}"
        exit 1
esac
exit $?
