#!/bin/bash

### BEGIN INIT INFO
# Provides:          clean-boa-env
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: safeguard to remove auto-healing pid files after reboot etc.
# Description:       safeguard to remove auto-healing pid files after reboot etc.
### END INIT INFO

PATH=/usr/local/bin:/usr/local/sbin:/opt/local/bin:/usr/bin:/usr/sbin:/bin:/sbin
NAME=clean-boa-env
DESC=clean-boa-env
PIDFILE=/var/run/clean-boa-env.pid

set -e

case "$1" in
  start)
    echo -n "Starting $DESC: "
    if [ -x "/bin/websh" ] && [ -L "/bin/sh" ] ; then
      _WEB_SH=`readlink -n /bin/sh`
      _WEB_SH=`echo -n $_WEB_SH | tr -d "\n"`
      if [ "$_WEB_SH" != "/bin/bash" ] ; then
        rm -f /bin/sh
        ln -s /bin/bash /bin/sh
      fi
    fi
    touch $PIDFILE
    if [ -e "/var/run/boa_wait.pid" ] ; then
      rm -f /var/run/boa_wait.pid
      echo "$NAME 1 done."
    else
      echo "$NAME 1 nothing to do."
    fi
    if [ -e "/var/run/boa_run.pid" ] ; then
      rm -f /var/run/boa_run.pid
      echo "$NAME 2 done."
    else
      echo "$NAME 2 nothing to do."
    fi
  ;;
  stop)
    echo -n "Stopping $DESC: "
    if [ -x "/bin/websh" ] && [ -L "/bin/sh" ] ; then
      _WEB_SH=`readlink -n /bin/sh`
      _WEB_SH=`echo -n $_WEB_SH | tr -d "\n"`
      if [ "$_WEB_SH" != "/bin/bash" ] ; then
        rm -f /bin/sh
        ln -s /bin/bash /bin/sh
      fi
    fi
    if [ -e "/var/run/boa_wait.pid" ] ; then
      rm -f /var/run/boa_wait.pid
      echo "$NAME done."
    else
      echo "$NAME nothing to do."
    fi
    if [ -e "/var/run/boa_run.pid" ] ; then
      rm -f /var/run/boa_run.pid
      echo "$NAME 2 done."
    else
      echo "$NAME 2 nothing to do."
    fi
    rm -f $PIDFILE
  ;;

  restart|force-reload)
    ${0} stop
    ${0} start
  ;;

  status)
    echo -n "$DESC status: "
    if [ -e "/var/run/boa_wait.pid" ] ; then
      echo "fail 1"
    else
      echo "OK 1"
      exit 1
    fi
    if [ -e "/var/run/boa_run.pid" ] ; then
      echo "fail 2"
    else
      echo "OK 2"
      exit 1
    fi
  ;;

  *)
    echo "Usage: /etc/init.d/$NAME {start|stop|restart|force-reload}" >&2
    exit 1
  ;;
esac

exit 0
