#!/bin/sh

# /etc/rc.d/rc.hdapsd
# Start/stop the HDAPS deamon 
# Copyright (c) 2008 alkos333 <me@alkos333.net>

# Define a quick function to alert that the expected config file is bad
bad_config() {
  printf "Error: /etc/hdapsd.conf either is not readable\n"
  printf "       or contains a syntax error.  Exiting...\n"
  exit 1
}

# Source in the config file
if [ -r /etc/hdapsd.conf ]; then
  . /etc/hdapsd.conf 2>/dev/null || bad_config
fi

HD_DEV=${HD_DEV:-/dev/sda}	# Defaults to /dev/sda
SENSITIVITY=${SENSITIVITY:-15}	# Defaults to 15
PIDFILE=${PIDFILE:-"/var/run/hdapsd.pid"}	# Default
USE_SYSLOG=${USE_SYSLOG:-1}	# 0=no  1=yes  Defaults to yes

if [ "$USE_SYSLOG" = "1" ]; then
  ENABLESYSLOG="-l"
else
  ENABLESYSLOG=""
fi

hdapsd_start() {
  if [ -f ${PIDFILE} ]; then
    printf "HDAPS appears to already be running...\n"
    printf "If that's not the case, then remove $PIDFILE and try again...\n"
    exit 1
  else
    # Sanity check, just in case
    if [ ! -b ${HD_DEV} ]; then
      printf "${HD_DEV} either does not exist or is not a block device.\n"
      printf "Check your configuration.  Exiting.\n"
      exit 1
    else 
      printf "Starting HDAPS daemon... \n"
      /usr/sbin/hdapsd -v -d $(basename ${HD_DEV}) -s ${SENSITIVITY} ${ENABLESYSLOG} \
        -a -b --pidfile=${PIDFILE} 1> /dev/null
    fi
  fi
}

hdapsd_stop() {
  printf "Stopping HDAPS daemon...\n"
  if [ -f ${PIDFILE} ]; then
    kill $(cat ${PIDFILE}) 2> /dev/null
    rm -f ${PIDFILE}
  else
    killall hdapsd 2>/dev/null
  fi
}

hdapsd_status() {
  if [ -f ${PIDFILE} ]; then
    printf "HDAPS daemon is running...\n"
  else
    printf "HDAPS daemon is stopped...\n"
  fi
}
  
case $1 in
  start)
    hdapsd_start
  ;;
  stop)
    hdapsd_stop
  ;;
  restart)
    hdapsd_stop
    hdapsd_start
  ;;
  status)
    hdapsd_status
  ;;
  *)
    printf "Usage $0 {start|stop|restart|status}\n"
    exit 1
  ;;
esac