#!/bin/sh
#
# by ymc-dabe
# A simple wrapper to the service command, that allows to restart a service,
# even it shows behavior, that is problematic to heartbeat (e.g. no support
# for "status" or a non-zero exit-code during restart).


ymcCommand=$4
USAGE="usage: $0 serviceToRestart {failed-restart-okay|failed-restart-not-okay} {failed-status-okay|failed-status-not}";

serviceToRestart=$1
allowFailuresString="$2 $3"

usage()
{
  echo $USAGE >&2
}

if [ $# != 4 ]; then
  usage
  exit 1
fi

restart_service()
{
  local whatToAsk=$1
  local exit_code=1

  if [ -x "/usr/sbin/service" ]; then
    /usr/sbin/service $serviceToRestart $1
    exit_code=$?
    if [ $exit_code -ne 0 ] && \
       [ $(echo $allowFailuresString | grep -c -F "failed-$whatToAsk-okay") -eq 1 ]; then
      exit_code=0
    fi
    exit $exit_code
  fi

  exit $exit_code
}


case $ymcCommand in
  start|stop)   restart_service restart;;
  status)       restart_service status;;
  *)            usage
                exit 1
                ;;
esac
