#!/bin/sh
#
### BEGIN INIT INFO
# Provides:          vpnagentd
# Required-Start:    $network $remote_fs
# Required-Stop:     $remote_fs
# Default-Start:     3 5
# Default-Stop:  
# Description:       Cisco AnyConnect Secure Mobility Client for Linux
# chkconfig:         345 85 25
# processname:       vpnagentd
### 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 Secure Mobility Client Agent"
RETVAL=0
PIDFILE="/var/run/vpnagentd.pid"

start() {
  # If TUN isn't supported by the kernel, try loading the module...
  /sbin/lsmod | grep tun > /dev/null 
  if [ $? -ne 0 ]; then
    /sbin/modprobe tun > /dev/null 2> /dev/null
    if [ $? -ne 0 ]; then
      # check for /dev/net/tun
      [ -c "/dev/net/tun" ] || echo  Warning: Unable to verify that the tun/tap driver is loaded.  Contact your system administrator for assistance.
    fi
  fi

  echo -n "Starting up $CLIENTNAME"
  /opt/cisco/anyconnect/bin/vpnagentd
  RETVAL=$?
  echo
  return $RETVAL
}

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

dostatus() {
  if [ -f "/etc/init.d/functions" ]; then
    status vpnagentd
  else
    if [ -f "/lib/lsb/init-functions" ]; then
      if [ -f $PIDFILE ]; then
        status_of_proc -p $PIDFILE vpnagentd "vpnagentd (pid `cat $PIDFILE`)" | sed 's/^[ \*]\+//'
      else
        echo "vpnagentd 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: vpnagentd {start|stop|restart|status}"
	exit 1
esac

exit $RETVAL
