#!/bin/sh

# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
#  Copyright (c) 2011 Openstack, LLC.
#  All Rights Reserved.
#
#     Licensed under the Apache License, Version 2.0 (the "License"); you may
#     not use this file except in compliance with the License. You may obtain
#     a copy of the License at
#
#          http://www.apache.org/licenses/LICENSE-2.0
#
#     Unless required by applicable law or agreed to in writing, software
#     distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#     WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#     License for the specific language governing permissions and limitations
#     under the License.
#
#
#
# nova-agent	Startup script for OpenStack nova guest agent
#
# chkconfig: 2345 15 85
# description: nova-agent is an agent meant to run on unix guest instances \
#              being managed by OpenStack nova.  Currently only works with \
#              Citrix XenServer for manipulating the guest through \
#              xenstore.
# processname: nova-agent
# pidfile: /var/run/nova-agent.pid
#

# PROVIDE: novaagent
# BEFORE: netif
# REQUIRE: FILESYSTEMS

. /etc/rc.subr

name="novaagent"
rcvar="nova_agent_enable"
start_cmd="novaagent_start"
stop_cmd="novaagent_stop"

prefix="/usr"
exec_prefix="${prefix}"
sbindir="/usr/bin"
datadir="${prefix}/share/nova-agent"
reallibdir="/usr/share/nova-agent/1.39.1/lib"

nova_agent="${sbindir}/nova-agent"
agent_config="/usr/share/nova-agent/nova-agent.py"
pidfile="/var/run/nova-agent.pid"
logfile="/var/log/nova-agent.log"
loglevel="info"

novaagent_start() {
  LD_LIBRARY_PATH="${reallibdir}"
  export LD_LIBRARY_PATH
  ${nova_agent} -q -p ${pidfile} -o ${logfile} -l ${loglevel} ${agent_config}
}

novaagent_stop() {
  num_tries=0
  while [ $num_tries -lt 10 ] ; do
    if [ ! -f ${pidfile} ] ; then
        break
    fi
    if [ $num_tries -eq 0 ] ; then
      pid=`cat ${pidfile}`
      if [ $? -eq 0 ] ; then
        kill $pid
      fi
    fi
    num_tries=`expr $num_tries + 1`
    sleep 1
  done
  rm -f ${pidfile}
}

load_rc_config $name
run_rc_command "$1"
