#!/bin/sh

# NOTE!
# This is a hacked up custom init script!
# 3PAR Host agent by default supports RH only, this is hacked up to work on Debian, don't lose it

### BEGIN INIT INFO
# Provides:        TpdHostAgent
# Required-Start:  $network $remote_fs $syslog
# Required-Stop:   $network $remote_fs $syslog
# Default-Start:   2 3 4 5
# Default-Stop:    1
# Short-Description: Start 3PAR Host Agent
### END INIT INFO

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

. /lib/lsb/init-functions

DAEMON=/usr/sbin/hagent
PIDFILE=/var/run/TpdHostAgent.pid

test -x $DAEMON || exit 5

if [ -r /etc/default/TpdHostAgent ]; then
	. /etc/default/TpdHostAgent
fi


LOCKFILE=/var/lock/TpdHostAgent

lock_TpdHostAgent() {
	if [ -x /usr/bin/lockfile-create ]; then
		lockfile-create $LOCKFILE
		lockfile-touch $LOCKFILE &
		LOCKTOUCHPID="$!"
	fi
}

unlock_TpdHostAgent() {
	if [ -x /usr/bin/lockfile-create ] ; then
		kill $LOCKTOUCHPID
		lockfile-remove $LOCKFILE
	fi
}

RUNASUSER=root
UGID=$(getent passwd $RUNASUSER | cut -f 3,4 -d:) || true

case $1 in
	start)
		log_daemon_msg "Starting 3PAR Host Agent" "TpdHostAgent"
		if [ -z "$UGID" ]; then
			log_failure_msg "user \"$RUNASUSER\" does not exist"
			exit 1
		fi
		lock_TpdHostAgent
  		start-stop-daemon --start --quiet --oknodo --pidfile $PIDFILE --startas $DAEMON 
		status=$?
		unlock_TpdHostAgent
		log_end_msg $status

		# Capture PID
		sleep 1
		ps auxww | grep "/usr/sbin/hagent" | grep -v grep | awk '{print $2}' >$PIDFILE
  		;;
	stop)
		log_daemon_msg "Stopping 3PAR Host Agent" "TpdHostAgent"
  		start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE
		log_end_msg $?
		rm -f $PIDFILE
  		;;
	restart|force-reload)
		$0 stop && sleep 2 && $0 start
  		;;
	try-restart)
		if $0 status >/dev/null; then
			$0 restart
		else
			exit 0
		fi
		;;
	reload)
		exit 3
		;;
	status)
		status_of_proc $DAEMON "3PAR Host Agent"
		;;
	*)
		echo "Usage: $0 {start|stop|restart|try-restart|force-reload|status}"
		exit 2
		;;
esac
