#!/bin/bash
#
# chkconfig: - 85 15
# description: Pound is a reverse proxy, load balancer and HTTPS front-end
# processname: pound
# config: /etc/pound/pound.cfg
# pidfile: /var/run/pound.pid

# Script Author: Simon Matter <simon.matter@invoca.ch>
# Version: 2011080200

# Source function library.
if [ -f /etc/init.d/functions ]; then
  . /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ] ; then
  . /etc/rc.d/init.d/functions
else
  exit 0
fi

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0

# Detect our basename
declare TMPNAME=$0
declare TMPPWD=$PWD
while [ -L $TMPNAME ]; do
  if [ ${TMPNAME/\/} != $TMPNAME ]; then
    cd ${TMPNAME%/*}
  fi
  TMPNAME=$(readlink ${TMPNAME##*/})
done
cd $TMPPWD
declare -r BASENAME=${TMPNAME##*/}
unset TMPNAME
unset TMPPWD

CFG_FILE="/etc/${BASENAME}/${BASENAME}.cfg"
if [ ! -f $CFG_FILE ]; then
  echo "${BASENAME}: configfile $CFG_FILE does NOT exist!"
  exit 1
fi

RETVAL=0

start() {
  echo -n $"Starting ${BASENAME}: "
  /usr/sbin/${BASENAME} -c > /dev/null 2>&1
  RETVAL=$?
  if [ $RETVAL -eq 0 ]; then
    cp -af /etc/localtime /var/empty/pound/etc/
    cp -af /lib64/libgcc_s*.so.* /var/empty/pound/lib64/
    daemon /usr/sbin/${BASENAME}
    RETVAL=$?
  else
    echo -n $"config error in $CFG_FILE"
    failure $"checking $BASENAME config file $CFG_FILE"
  fi
  echo
  [ $RETVAL -eq 0 ] && touch /var/lock/subsys/${BASENAME}
  return $RETVAL
}

stop() {
  echo -n $"Shutting down ${BASENAME}: "
  killproc $BASENAME
  RETVAL=$?
  rm -f /var/empty/pound/etc/localtime
  rm -f /var/empty/pound/lib64/libgcc_s*.so.*
  echo
  [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/${BASENAME}
  return $RETVAL
}

restart() {
  stop
  start
}

svcstatus() {
  status $BASENAME
}

condrestart() {
  [ -e /var/lock/subsys/${BASENAME} ] && restart || :
}

# See how we were called.
case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    restart
    ;;
  reload)
    restart
    ;;
  condrestart)
    condrestart
    ;;
  status)
    svcstatus
    ;;
  *)
    echo $"Usage: $BASENAME {start|stop|restart|reload|condrestart|status}"
    RETVAL=1
esac
 
exit $RETVAL
