#!/bin/sh
#
#
# Starts the thinkfan daemon
#
# chkconfig: 123 69 68
# description: Start stops the thinkfan daemon 
# processname: thinkfan
# config: /etc/thinkfan.conf

. /etc/init.d/functions

prefix=/usr
exec_prefix=/usr
sbindir=${exec_prefix}/sbin

THINKFAN_BIN=${sbindir}/thinkfan 

# Sanity checks.
[ -x $THINKFAN_BIN ] || exit 0

PIDFILE=/var/run/thinkfan.pid

thinkfan_start()
{
  
  # Just in case the pidfile is still there, we may need to nuke it.
  if [ -e "$PIDFILE" ]; then
    rm -f $PIDFILE
  fi

  $THINKFAN_BIN
}

thinkfan_status()
{
  local pidlist=`cat $PIDFILE 2>/dev/null`
  if [ -z "$pidlist" ]; then
    return 1
  fi
  local command=`ps -p $pidlist -o comm=`
  if [ "$command" != 'thinkfan' ]; then
    return 1
  fi
}

thinkfan_stop()
{
  local pidlist=`cat $PIDFILE 2>/dev/null`
  if [ ! -z "$pidlist" ]; then
    kill $pidlist &>/dev/null
    rm -f $PIDFILE &>/dev/null
	fi
}

thinkfan_restart()
{
  thinkfan_stop
  sleep 3
  thinkfan_start
}

case "$1" in
'start')
  if ( ! thinkfan_status ); then
    thinkfan_start
  else
    echo "Thinkfan is already running (will not start it twice)."
  fi
		;;
'stop')
  thinkfan_stop
		;;
'restart')
  thinkfan_restart
		;;
'status')
  if ( thinkfan_status ); then
    echo "Thinkfan is currently running"
  else
    echo "Thinkfan is not running."
  fi
		;;
*)
  echo "usage $0 start|stop|status|restart"
esac
