#!/bin/bash
#
# rcoracle - Wrapper for /usr/sbin/service:
#   1. When called with "status", additionally dump dependencies to console
#   2. When called with "stop", block until all depending units are inactive or
#      timeout has elapsed. Timeout can be set by environment variable 
#      RCORACLE_TIMEOUT_STOP in /etc/sysconfig/oracle. Default is 240 seconds.

test -f /etc/sysconfig/oracle && source /etc/sysconfig/oracle
TIMEOUT=${RCORACLE_TIMEOUT_STOP:-240}
/usr/sbin/service oracle $@
rc=$?
case $1 in
  status)
    # If a depending unit has failed and was removed after, it is still reported as
    # a dependency. "reset-failed" fixes this issue.
    /usr/bin/systemctl reset-failed $(/usr/bin/systemctl list-dependencies --plain oracle.target)
    /usr/bin/systemctl list-dependencies oracle.target
   ;;
   stop)
     if test $rc -eq 0; then
       # block until all dependencies are inactive (or timeout has reached)
       dep=$(/usr/bin/systemctl --plain list-dependencies oracle.target)	
       # Beause of https://bugzilla.redhat.com/show_bug.cgi?id=1417251 (DUPLICATE 2017)
       # and https://bugzilla.redhat.com/show_bug.cgi?id=1073481 (WONTFIX 2014)
       # do not use systemctl is-activem because it is not reporting correctly!
       while /usr/bin/systemctl show $dep | grep "^ActiveState=" | grep -qv "inactive\|failed"; do
         test $[--TIMEOUT] -gt 0 || break # timeout elapsed
         sleep 1;
       done
       test $TIMEOUT -le 0 && rc=-111 && echo "Timed out..." >&2
     fi
  ;;
esac
exit $rc
