#!/bin/sh
#
# Copyright 2007 VMware, Inc.  All rights reserved.
#

# Basic support for IRIX style chkconfig 
# chkconfig: 3 99 07
# description: AutoStart VMs

# load system helper functions.
. /etc/init.d/functions

PATH=/sbin:/usr/sbin:/bin:/usr/bin
export PATH

VIMSH=/usr/bin/vimsh
AUTOPOWERON=/usr/bin/vmware-autopoweron.sh
subsys=vmware-autostart

#
# Utilities
#

# Execute a macro
vmware_exec() {
   local msg="$1"  # IN
   local func="$2" # IN
   shift 2

   echo -n '   '"$msg"

   "$func" "$@" >/dev/null 2>&1

   if [ "$?" -gt 0 ]; then
      echo_failure
      echo
      return 1
   fi

   echo_success
   echo
   return 0
}

# AutoStart vms if any
vmware_autostart_vms() {
   vmware_exec "Starting VMs" "$AUTOPOWERON" &
}

# AutoStop vms if any
vmware_autostop_vms() {
   vmware_exec "Stopping VMs" "$VIMSH" -n -e 'hostsvc/autostartmanager/autostop'
}

case "$1" in
  start)
	echo -n "Starting AutoStart VM service:"
 
	vmware_autostart_vms

        [ -d /var/lock/subsys ] || mkdir -p /var/lock/subsys
        touch /var/lock/subsys/$subsys

	echo_success
	echo
        ;;

  stop)
	vmware_autostop_vms
	;;

  restart)
	"$0" stop && "$0" start
	;;

  *)
	echo "Usage: `basename "$0"` {start|stop|restart}"
	exit 1
esac

exit 0
