#!/bin/sh
#
### BEGIN INIT INFO
# Provides:          acnvmagent
# Required-Start:    $network $remote_fs
# Required-Stop:     $remote_fs
# Default-Start:     3 5
# Default-Stop:  
# Description:       Cisco AnyConnect Network Visibility Client for Linux
# chkconfig:         345 85 25
# processname:       acnvmagent
### END INIT INFO

# Source function library 
  if [ -f "/etc/init.d/functions" ]; then
    # Redhat will have library here
    . /etc/init.d/functions
  else
    if [ -f "/lib/lsb/init-functions" ]; then
      # Ubuntu will have library here
      . /lib/lsb/init-functions
    fi
  fi

CLIENTNAME="Cisco AnyConnect Network Visibility Client"
RETVAL=0
PIDFILE="/var/run/acnvmagent.pid"

start() {
  echo -n "Starting up $CLIENTNAME"
  /opt/cisco/anyconnect/NVM/bin/acnvmagent
  RETVAL=$?
  echo
  return $RETVAL
}

stop() {
  echo -n "Shutting down $CLIENTNAME"
  NVMPID=$( pidof /opt/cisco/anyconnect/NVM/bin/acnvmagent )
  if [ "x${NVMPID}" != "x" ] ; then
    # wait until acnvmagent dies, or 10 secs
    kill ${NVMPID} > /dev/null 2>/dev/null
    NVMPID=$( pidof /opt/cisco/anyconnect/NVM/bin/acnvmagent )
    t=0
    while [ "x${NVMPID}" != "x" -a $t -le 10 ]; do 
      sleep 1
      t=$( expr $t + 1 )
      NVMPID=$( pidof /opt/cisco/anyconnect/NVM/bin/acnvmagent )
    done
    if [ "x${NVMPID}" != "x" ] ; then
       kill -KILL ${NVMPID} > /dev/null 2>/dev/null
    fi
  fi
  RETVAL=$?
  echo
  return $RETVAL
}

dostatus() {
  if [ -f "/etc/init.d/functions" ]; then
    status acnvmagent
  else
    if [ -f "/lib/lsb/init-functions" ]; then
      if [ -f $PIDFILE ]; then
        status_of_proc -p $PIDFILE acnvmagent "acnvmagent (pid `cat $PIDFILE`)" | sed 's/^[ \*]\+//'
      else
        echo "acnvmagent is stopped "
      fi
    fi
  fi
}

restart() {
	stop
	start
}

# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart)
    restart
    ;;
  status)
	dostatus
	;;
  *)
	echo "Usage: acnvmagent {start|stop|restart|status}"
	exit 1
esac

exit $RETVAL
