#! /bin/sh
# Copyright (c)1995 SuSE GmbH Nuernberg, Germany.
# 
# Author: SuSE Oracle Team <feedback@suse.de>
# Homepage: http://www.suse.com/oracle/
# 
### BEGIN INIT INFO
# Provides: oracle
# Required-Start: $network $syslog $remote_fs raw
# Should-Start: ocfs2 sshd
# Should-Stop: ocfs2
# Required-Stop: $network $syslog $remote_fs
# Default-Start: 3 5
# Default-Stop: 0 1 2 6
# Description: Start the Oracle database
### END INIT INFO


# Shell functions sourced from /etc/rc.status:
#      rc_check         check and set local and overall rc status
#      rc_status        check and set local and overall rc status
#      rc_status -v     ditto but be verbose in local rc status
#      rc_status -v -r  ditto and clear the local rc status
#      rc_failed        set local and overall rc status to failed
#      rc_reset         clear local rc status (overall remains)
#      rc_exit          exit appropriate to overall rc status
SYSTEMD_NO_WRAP=1
. /usr/lib/orarun/rc.status

start_oracle_crs()
{
      echo -n "  - Starting Oracle CRS..."
      if [ "${START_ORACLE_RAC_CRS:-no}" = "yes" ]; then
        /etc/init.d/init.crs start >& /dev/null
        rc_status -v -r
        sleep 2
        kill -1 1
      else
        if [ ${START_ORACLE_RAC_CRS:-no} = "cannot" ]; then
          rc_status -s
        else
          rc_status -u
        fi
      fi

}

start_oracle_ocfs2()
{
      echo -n "  - Starting Oracle Cluster Filesystem..."
      if [ "${START_ORACLE_RAC_OCFS2:-no}" = "yes" ]; then
        # Start o2cb If it's configured and not started
        if ! ( (/usr/bin/systemctl is-enabled --quiet o2cb) ); then
          systemctl start o2cb >& /dev/null;
        fi
        systemctl start ocfs2 >& /dev/null
        rc_status -v -r
        echo -n "  - Mounting Oracle Cluster Filesystem(s)..."
        $MOUNT -a -t ocfs2
        rc_status -v -r
      else
        if [ ${START_ORACLE_RAC_OCFS2:-no} = "cannot" ]; then
          rc_status -s
        else
          rc_status -u
        fi
      fi
}

start_oracle_css()
{
      if [ -x /etc/init.d/init.cssd -a ! -x /etc/init.d/init.crs ]; then
        echo -n "  - Starting css daemon..."
        /etc/init.d/init.cssd start
        rc_status -v -r
        kill -1 1
        sleep 5
      fi
}

start_oracle_listener()
{
      echo -n "  - Starting Listener..."
      if [ "${START_ORACLE_DB_LISTENER:-no}" = "yes" ]; then
        $ORACLE_HOME/bin/lsnrctl start > /dev/null
        rc_status -v -r
      else
        if [ ${START_ORACLE_DB_LISTENER:-no} = "cannot" ]; then
          rc_status -s
        else
          rc_status -u
        fi
      fi
}

start_oracle_apache()
{
      echo -n "  - Starting Apache..."
      if [ "${START_ORACLE_DB_APACHE:-no}" = "yes" ]; then
        SSL=""
        if [ ${ORACLE_DB_APACHE_USE_SSL} = "yes" ]; then
          SSL="ssl"
        fi
        export DISPLAY=:42.0; $ORACLE_HOME/Apache/Apache/bin/apachectl start$SSL >& /dev/null
        if [ "$?" != "0" ]; then rc_failed; else rc_failed 0; fi
        rc_status -v -r
      else
        if [ ${START_ORACLE_DB_APACHE:-no} = "cannot" ]; then
          rc_status -s
        else
          rc_status -u
        fi
      fi
}

start_oracle_app_server()
{
      echo -n "  - Starting Application Server..."
      if [ "${START_ORACLE_AS_ALL:-no}" = "yes" ]; then
        $ORACLE_HOME/opmn/bin/opmnctl startall > /dev/null
        if [ "$?" != "0" ]; then rc_failed; else rc_failed 0; fi
        rc_status -v -r
      else
        if [ ${START_ORACLE_AS_ALL:-no} = "cannot" ]; then
          rc_status -s
        else
          rc_status -u
        fi
      fi
}

start_oracle_app_server_console()
{
      echo -n "  - Starting Application Server Console..."
      if [ "${START_ORACLE_AS_CONSOLE:-no}" = "yes" ]; then
        $ORACLE_HOME/bin/emctl start iasconsole > /dev/null
        if [ "$?" != "0" ]; then rc_failed; else rc_failed 0; fi
        rc_status -v -r
      else
        if [ ${START_ORACLE_AS_CONSOLE:-no} = "cannot" ]; then
          rc_status -s
        else
          rc_status -u
        fi
      fi
}

start_oracle_db_agent()
{
      echo -n "  - Starting Agent..."
      if [ "${START_ORACLE_DB_AGENT:-no}" = "yes" ]; then
        $AGENT_START > /dev/null
        rc_status -v -r
      else
        if [ ${START_ORACLE_DB_AGENT:-no} = "cannot" ]; then
          rc_status -s
        else
          rc_status -u
        fi
      fi
}

start_oracle_db_emanager()
{
      echo -n "  - Starting Enterprise Manager..."
      if [ "${START_ORACLE_DB_EMANAGER:-no}" = "yes" ]; then
        echo
        for SID in `sed -n 's/^\([^#+]*\):.*:Y/\1/p' /etc/oratab`
        do
            echo -n "    Starting DB Console for $SID"
            export ORACLE_SID=$SID 
            $ORACLE_HOME/bin/emctl start dbconsole > /dev/null < /dev/null &
            sleep 5
        done
        rc_status -v -r
      else
        if [ ${START_ORACLE_DB_EMANAGER:-no} = "cannot" ]; then
          rc_status -s
        else
          rc_status -u
        fi
      fi
}

start_oracle_db_isqlplus()
{
      echo -n "  - Starting iSQLPLUS Manager..."
      if [ "${START_ORACLE_DB_ISQLPLUS:-no}" = "yes" ]; then
        $ORACLE_HOME/bin/isqlplusctl start > /dev/null
        rc_status -v -r
      else
        if [ ${START_ORACLE_DB_ISQLPLUS:-no} = "cannot" ]; then
          rc_status -s
        else          
          rc_status -u
        fi
      fi
}

start_oracle_db_ifs()
{
      echo -n "  - Starting Oracle Internet Filesystem..."
      if [ "${START_ORACLE_DB_IFS:-no}"  = "yes"  ]; then
        echo -n " ${extd}Not yet implemented.$norm"
        rc_status -s
      else
        if [ ${START_ORACLE_DB_IFS:-no} = "cannot" ]; then
          rc_status -s
        else
          rc_status -u
        fi
      fi
}

start_oracle_db_oid()
{
      echo -n "  - Starting Oracle Internet Directory..."
      if [ "${START_ORACLE_DB_OID:-no}" = "yes" ]; then
        echo -n " ${extd}Not yet implemented.$norm"
        rc_status -s
      else
        if [ ${START_ORACLE_DB_OID:-no} = "cannot" ]; then
          rc_status -s
        else
          rc_status -u
        fi
      fi
}

status_agent()
{
      if [ -x $ORACLE_HOME/bin/agentctl ]; then
        state=up
        agentctl status | grep "Could not contact agent" >/dev/null && state=down
        echo "${extd}Intelligent Agent:$norm $state"
        echo
      fi
}

status_listener()
{
      if [ -x $ORACLE_HOME/bin/lsnrctl ]; then
        state=up
        $ORACLE_HOME/bin/lsnrctl status | grep "[nN]o [lL]istener" >/dev/null && state=down
        echo "${extd}TNS-Listener:$norm $state"
        echo
      fi
}

status_cluster_db()
{
      echo "${extd}Cluster Database Status$norm"
      if ( $CHECKPROC $ORA_CRS_HOME/bin/ocssd.bin ); then
        DBNAME="`$ORA_CRS_HOME/bin/srvctl config database`"
        # echo "Database Name : " $DBNAME
        if [ "$DBNAME" != "" ]; then
          $ORA_CRS_HOME/bin/srvctl status database -d `$ORA_CRS_HOME/bin/srvctl config database`
        fi
      fi
      echo
}

stop_cssd()
{
      # This case is for Single Instance Database using ASM storage (Not RAC)
      # for RAC init.crs will do this
      if [ -x /etc/init.d/init.cssd -a ! -x /etc/init.d/init.crs ]; then
        echo -n "Shutting down CSSD:"
        /etc/init.d/init.cssd stop >/dev/null
        rc_status -v -r
        kill -1 1
        sleep 5
      fi
}

print_header()
{
    echo
    echo "#############################################################################"
    echo "#                 Begin of   O R A C L E   $1 section                  #"
    echo "#############################################################################"
    echo
}

# catch mis-use right here at the start
if [  "$1" != "start"  -a  "$1" != "stop"  -a  "$1" != "status" -a "$1" != "restart" ]; then
    echo "Usage: $0 {start|stop|status|restart}"
    exit 1
fi


. /usr/lib/orarun/common.sh


# First reset status of this service
rc_reset

# Here we finally get to do the real work.
case "$1" in
  start)
    print_header "startup"

    ora_environment start

    # 
    # Check if we really have all the Oracle components we are told to start
    # 
    if [ "$ORACLE_RAC" = "yes" ]; then
      if [ ! -x $LOAD_OCFS2 -a ${START_ORACLE_RAC_OCFS2:-no} = "yes" ]; then
        echo "${warn}Can't find needed file: $LOAD_OCFS2 - Setting START_ORACLE_RAC_OCFS2 = no $norm"
        START_ORACLE_RAC_OCFS2="cannot";
      fi

      if [ ! -x /etc/init.d/init.crs -a ${START_ORACLE_RAC_CRS:-no} = "yes" ]; then
        echo "${warn}Can't find needed file: init.crs - Setting START_ORACLE_RAC_CRS = no $norm"
        START_ORACLE_RAC_CRS="cannot";
      fi
    else
      if [ ! -x $ORACLE_HOME/bin/dbstart -a ${START_ORACLE_DB:-no} = "yes" ]; then
        echo "${warn}Can't find needed file: dbstart - Setting START_ORACLE_DB = no $norm"
        START_ORACLE_DB="cannot";
      fi

      if [ ! -x $ORACLE_HOME/bin/lsnrctl -a ${START_ORACLE_DB_LISTENER:-no} = "yes" ]; then
        echo "${warn}Can't find needed file: lsnrctl - Setting START_ORACLE_DB_LISTENER = no $norm"
        START_ORACLE_DB_LISTENER="cannot";
      fi
     
      if [ ! -x $ORACLE_HOME/Apache/Apache/bin/apachectl -a ${START_ORACLE_DB_APACHE:-no} = "yes" ]; then
        echo "${warn}Can't find needed file: apachectl - Setting START_ORACLE_DB_APACHE = no $norm"
        START_ORACLE_DB_APACHE="cannot";
      fi
    fi

    if [ ! -x $ORACLE_HOME/bin/emctl -a ${START_ORACLE_DB_EMANAGER:-no} = "yes" ]; then
      echo "${warn}Can't find needed file: emctl - Setting START_ORACLE_DB_EMANAGER = no $norm"
      START_ORACLE_DB_EMANAGER="cannot";
    fi

    if [ ! -x $ORACLE_HOME/bin/isqlplusctl -a ${START_ORACLE_DB_ISQLPLUS:-no} = "yes" ]; then
      echo "${warn}Can't find needed file: isqlplusctl - Setting START_ORACLE_DB_ISQLPLUS = no $norm"
      START_ORACLE_DB_ISQLPLUS="cannot";
    fi

    #   Agent Version check only if it's set
    if [ ${START_ORACLE_DB_AGENT:-no} = "yes" ]; then
      case $AGENT_VERSION in
         10g)
              if [ ! -x $ORACLE_HOME/bin/agtctl -a ${START_ORACLE_DB_AGENT:-no} = "yes" ]; then
                echo "${warn}Can't find needed file: agtctl - Setting START_ORACLE_DB_AGENT = no $norm"
                START_ORACLE_DB_AGENT="cannot"
              fi
              ;;
        10gA)
              if [ ! -x $AGENT_HOME/bin/emctl -a ${START_ORACLE_DB_AGENT:-no} = "yes" ]; then
                echo "${warn}Can't find needed file: emctl - Setting START_ORACLE_DB_AGENT = no $norm"
                START_ORACLE_DB_AGENT="cannot"
              fi
              ;;
          *)
              echo "Oracle Agent undefinied or not properly set. Please check."
              ;;
      esac
    fi

    echo

    # Set kernel parameters for Oracle (was extracted to oracle-setup)
    
    rc_reset

    if [ "$ORACLE_RAC" = "yes" ]; then
      start_oracle_ocfs2

      rc_reset

      start_oracle_crs

      rc_reset

      # Find Better way to start Enterprise Manager in RAC
      if [ "${START_ORACLE_DB_EMANAGER:-no}" = "yes" ]; then
        echo -n "  - Starting Enterprise Manager... "
        rc_status -v -s
      fi

    else
      # For Single Instance Database (ASM)
      start_oracle_css

      rc_reset

      start_oracle_listener

      rc_reset

      echo
      echo "  + Starting Database(s)..."
      if [ "${START_ORACLE_DB:-no}" = "yes" ]; then
        # Fix log directories: 9iR2 RAC installation forgets these directories on the nodes
        $MKDIR -p $ORACLE_HOME/rdbms/audit $ORACLE_HOME/rdbms/log $ORACLE_HOME/network/log 2>/dev/null
        # The database will not start if the entry in /etc/oratab is "N"
        cat /etc/oratab | while read LINE
        do
          case $LINE in
            \#*) # skip over comment-line in oratab
                 ;;
              *)
                 # Proceed only if third field is 'Y'.
                 if [ "`echo $LINE | awk -F: '{print $3}' -`" = "N" ] ; then
                   ORACLE_SID=`echo $LINE | awk -F: '{print $1}' -`
                   ORACLE_HOME=`echo $LINE | awk -F: '{print $2}' -`
                   echo; echo -n "No start entry for SID $ORACLE_SID at $ORACLE_HOME in /etc/oratab"
                   rc_status -s
                 fi
                 ;;
          esac
        done

        echo -n "    "
        # $ORACLE_HOME is required for dbstart to avoid warning message
        $ORACLE_HOME/bin/dbstart $ORACLE_HOME

        rc_status
        echo -n "    Status of Oracle database(s) start:"
        rc_status -v -r
        echo
      else
        if [ ${START_ORACLE_DB:-no} = "cannot" ]; then
          rc_status -s
        else
          rc_status -u
        fi
        echo
      fi

      rc_reset

      start_oracle_apache

      rc_reset

      start_oracle_app_server

      rc_reset

      start_oracle_app_server_console

      rc_reset

      start_oracle_db_agent

      rc_reset

      start_oracle_db_emanager

      rc_reset

      start_oracle_db_isqlplus

      rc_reset

      start_oracle_db_ifs

      rc_reset

      start_oracle_db_oid
    fi
    ;;
  stop)
    print_header "shutdown"

    ora_environment stop

    echo "Shutting down Oracle services (only those running)"; echo

    if [ "$ORACLE_RAC" = "yes" ]; then
      # TO DO - Find Better way to shutdown
      # test -x $ORACLE_HOME/bin/emctl           && test "${START_ORACLE_DB_EMANAGER:-no}" = "yes"      && echo -n "Shutting down Enterprise Manager: " && ($ORACLE_HOME/bin/emctl stop dbconsole > /dev/null; rc_status -v -r)

      # init.crs stop prints Shutting down message
      test -x /etc/init.d/init.crs    && $CHECKPROC $ORA_CRS_HOME/bin/ocssd.bin && test  "${START_ORACLE_RAC_CRS:-no}" = "yes"              && echo -n   && (/etc/init.d/init.crs stop; sleep 5; rc_status -v -r)

      test -x /etc/init.d/ocfs2                   &&  test "${START_ORACLE_RAC_OCFS2:-no}" = "yes"         && echo -n "Unmounting OCFS2 Filesystem: " && ($UMOUNT -t ocfs2 -a; rc_status -v -r)

     else
      test -x $ORACLE_HOME/Apache/Apache/bin/apachectl && $CHECKPROC $ORACLE_HOME/Apache/Apache/bin/httpd  && echo -n "Shutting down Apache: " && (export ORACLE_HOME=$ORACLE_HOME TNS_ADMIN=$TNS_ADMIN; $ORACLE_HOME/Apache/Apache/bin/apachectl stop > /dev/null; rc_status -v -r)

      # Shutting Down Agent
      if [ ${START_ORACLE_DB_AGENT:-no} = "yes" ]; then
        case $AGENT_VERSION in
          10g)
               test -x $AGENT_PROG && $CHECKPROC $AGENT_PROG  && echo -n "Shutting down Agent: " && ($AGENT_STOP > /dev/null; rc_status -v -r)
               ;;
         10gA)
               test -x $AGENT_PROG && $CHECKPROC $AGENT_PROG  && echo -n "Shutting down Agent: " && ($AGENT_STOP > /dev/null; rc_status -v -r)
               ;;
           *)
               echo "Oracle Agent undefinied or not properly set. Please check."
               ;;
        esac
      fi

      test -x $ORACLE_HOME/bin/isqlplusctl        && test  "${START_ORACLE_DB_ISQLPLUS:-no}" = "yes"        && echo -n "Shutting down iSQLPLUS Manager: " && ($ORACLE_HOME/bin/isqlplusctl stop > /dev/null; rc_status -v -r)

      test -x $ORACLE_HOME/bin/emctl           && test "${START_ORACLE_DB_EMANAGER:-no}" = "yes"      && echo -n "Shutting down Enterprise Manager: " && ($ORACLE_HOME/bin/emctl stop dbconsole > /dev/null; rc_status -v -r)

      test -x $ORACLE_HOME/bin/lsnrctl           && test  "${START_ORACLE_DB_LISTENER:-no}" = "yes"      && $CHECKPROC $ORACLE_HOME/bin/tnslsnr              && echo -n "Shutting down Listener: " && ($ORACLE_HOME/bin/lsnrctl stop > /dev/null; rc_status -v -r)

      test -x $ORACLE_HOME/bin/dbshut            && test  "${START_ORACLE_DB:-no}" = "yes"      && $CHECKPROC $ORACLE_HOME/bin/oracle               && echo -n "Shutting down Database: " && ($ORACLE_HOME/bin/dbshut > /dev/null; rc_status -v -r)

      stop_cssd
    fi
    ;;
  status)
    print_header "status"

    ora_environment status

    echo "${extd}Kernel Parameters$norm"
    echo -n "Shared memory:"
    echo -n "  SHMMAX=" `cat /proc/sys/kernel/shmmax`
    echo -n "  SHMMNI=" `cat /proc/sys/kernel/shmmni`
    echo    "  SHMALL=" `cat /proc/sys/kernel/shmall`
    echo -n "Semaphore values:"
    echo    "  SEMMSL, SEMMNS, SEMOPM, SEMMNI: " `cat /proc/sys/kernel/sem`
    echo

    if [ "$ORACLE_RAC" = "yes" ]; then
      echo "${extd}OCFS2 Status$norm"
      systemctl status ocfs2
      echo

      echo "${extd}Oracle Clusterware Status$norm"
      $CHECKPROC $ORA_CRS_HOME/bin/ocssd.bin &&( $ORA_CRS_HOME/bin/crsctl check crs )
      echo
    fi

    if [ "$ORACLE_RAC" = "yes" ]; then
      status_cluster_db
    else
      if [ -x $ORACLE_HOME/bin/oracle ]; then
        echo "${extd}Database-Instances$norm"
        # loop over the instances (very simple !!!)
        IFS=:
        grep -v '^\(#\|$\)' /etc/oratab | while read sid ohome autostart ; do
          state=up
          export ORACLE_SID=$sid;
          sqlplus /nolog <<-! 2>/dev/null | grep ORA-01034 >/dev/null && state=down
connect / as sysdba
show sga
!
          echo "Instance $sid is $state (autostart: $autostart)"
        done
        echo
      fi

      status_listener

      numhttpd=`ps -e | grep httpd | wc -l | sed 's/ //g'`
      state=up
      if [ "$numhttpd" -lt 1 ] ; then state=down ; fi
      echo "${extd}Web-Server (Apache httpd):$norm $state ($numhttpd processes)"
      echo

      status_agent
    fi

    echo "${extd}Process list for user oracle:$norm"
    ps U oracle
    ps ax | grep oracm | grep -v grep
    ;;
  restart)
    ## Stop the service and regardless of whether it was
    ## running or not, start it again.
    $0 stop
    $0 start
    ;;
  *)
    echo "Usage: $0 {start|stop|status|restart}"
    exit 1
esac

echo
echo "#############################################################################"
echo "#                      End of   O R A C L E   section                       #"
echo "#############################################################################"
echo

# Global return value of this script is "success", always. We have too many
# individual return values...
rc_status -r

rc_exit

