#!/bin/bash

sid=$2

export ORACLE_SID=${sid}
ORAENV_ASK=NO
. /usr/local/bin/oraenv > /dev/null 2>&1

function getPID() {
    echo `ps -ef | grep "$1" | grep -v grep | awk '{ print $2 }'`
}

start() {
    # Make sure a TNS Listener is running.  If none
    # is found, start one from the current home.

    [ ! `getPID "tnslsnr"` ] && lsnrctl start

    # If the process monitor for the given sid
    # is running, assume the database is up
    # and exit.

    [ `getPID "ora_pmon_$sid"` ] && exit

    # Start the database and make sure it gets
    # registered with the listener right away.

    sqlplus -s -L << _EOF
      connect / as sysdba
      startup

      -- Force registration with the listener.
      alter system register;
      exit
_EOF
}

stop() {
    # If the process monitor for the given sid
    # is NOT running, assume the database is down
    # and exit.

    [ ! `getPID "ora_pmon_${sid}"` ] && exit

    sqlplus -L -s <<_EOF
      connect / as sysdba
      shutdown immediate
      exit
_EOF

    # *** NOTE: The listener is never shutdown!
}

case $1 in
[Ss][Tt][Aa][Rr][Tt])
    start
;;

[Ss][Tt][Oo][Pp])
    stop
;;
esac

