#! /bin/bash
#
# /etc/init.d/wsman
#
#   and its symbolic links
#
# Provides: wsman
# chkconfig: 35 99 10
# description: wsman server
#

# source function library

. /etc/init.d/functions

export LD_LIBRARY_PATH=/usr/lib/vmware:/usr/lib/vmware/hostd:${LD_LIBRARY_PATH}

watchdog=/usr/bin/vmware-watchdog


# wsman specific command line options
OPTIONS="-d"

WSMAND=/sbin/openwsmand
MSG="WS-Management Server"
subsys=wsman

TEMPLATE_FILE="/etc/openwsman/openwsman.conf.tmpl"
CONFIG_FILE="/etc/openwsman/openwsman.conf"
OEM_FILE="/etc/openwsman/oem.conf"
TEMP_FILE="/etc/openwsman/openwsman.conf.temp"

#
# Combine the oem.conf file with the openwsman.conf.tmpl
# file to create the openwsman.conf file.
#

reconfigure() {
  #
  # If the template file does not exist then exit,
  # since there is no way to create a configuration
  # file.
  #
  [ -e $TEMPLATE_FILE ] || exit 1

  #
  # If an openwsman.conf file is already present
  # then delete the file, since we will be
  # recreating the file.
  #

  if [ -e $CONFIG_FILE ]; then
         rm $CONFIG_FILE
         cp $TEMPLATE_FILE $TEMP_FILE
         touch $CONFIG_FILE
         else
                cp $TEMPLATE_FILE $TEMP_FILE
                touch $CONFIG_FILE
  fi

  #
  # Test to see if the oem file is present. If so,
  # then add the namespaces to the default
  # config file.
  #
  if [ -e $OEM_FILE ]; then
    while read line; do
      if echo "$line" | grep -q vendor_namespace; then
        while read line2; do
          line="$line,$line2"
        done<$OEM_FILE
        line=`echo $line | sed 's/\,*$//'`
      fi
    echo $line 1>> $CONFIG_FILE
    done<$TEMP_FILE
    else
        cp $TEMP_FILE $CONFIG_FILE
  fi
  rm $TEMP_FILE
}

start() {
   echo -n "Starting ${MSG}..."
   [ -d /var/lock/subsys ] || mkdir -p /var/lock/subsys
   touch /var/lock/subsys/$subsys
   reconfigure
   $watchdog -s openwsmand -u 60 -q 5 $WSMAND $OPTIONS > /dev/null 2>&1 &
   success
   echo
}

stop() {
   echo -n "Stopping ${MSG}..."
   $watchdog -k openwsmand > /dev/null 2>&1

   # Check to make sure it's running first
   pid=`pidof -o $$ -o $PPID -o %PPID ${WSMAND}`
   if [ -n "$pid" ] ; then
      # It's still running, so kill it forcefully
      killproc ${WSMAND}
      RETVAL=$?
      echo
      rm -f /var/lock/subsys/$subsys
      return $RETVAL
   else
      success
      echo
      return 0
   fi
}

restart() {
   ## If first returns OK call the second, if first or
   ## second command fails, set echo return value.
   $0 stop  &&  $0 start
}

case "$1" in
   start)
      if $watchdog -r openwsmand > /dev/null 2>&1 ; then
	 echo "wsman is already running"
      else
	 start
      fi
      ;;
   stop)
      # Don't process the queue on stop so we can shutdown quickly
      stop
      ;;
   restart)
      restart
      ;;
   reload)
      restart
      ;;
   status)
      status ${WSMAND}
      ;;
   *)
      echo "Usage: $0 {start|stop|status|restart|reload}"
      exit 1
      ;;
esac
