#============================================================================
# Title       : ora-sid
# Description : Quickly change the ORACLE_SID to another valid one
# Author      : Bart Sjerps <bart@dirty-cache.com>
# License     : GPLv3+
# Version     : 1.0
# ---------------------------------------------------------------------------
# Revision history:
# 2015-02-15 : Created
# 2016-12-24 : Select next SID if no parameters are given
# ---------------------------------------------------------------------------

# As this script gets sourced we don't want to define a usage() function.
# Dump a usage message if user does not provide a (valid) SID instead.
#
#============================================================================
# Main section - parsing options etc
# ---------------------------------------------------------------------------
test -f /etc/oratab || return 0

if test $# -eq 0; then
  export ORACLE_SID=$(awk -F: 'NF==3 && $1 !~ "#" && $1 !~ "+" { print $1 ; }' /etc/oratab /etc/oratab | awk -vS=$ORACLE_SID '$1==S {getline;print;exit}')
  test -z "$ORACLE_SID" && export ORACLE_SID=$(awk -F: 'NF==3 && $1 !~ "#" && $1 !~ "+" { print $1 ; exit ; }' /etc/oratab)
  export ORAENV_ASK=NO
  . oraenv
elif awk -vS=${1:-none} -F: '$1==S { f=1 } END {exit !f;}' /etc/oratab; then
  export ORACLE_SID=$1
  export ORAENV_ASK=NO
  . oraenv
else
  cat <<- EOF

	Nonvalid ORACLE_SID (not in /etc/oratab)!

	Usage: sid [oracle sid]

	This script can be sourced with a valid ORACLE_SID. It provides
	bash completion and an alias to make this work.

	Call without parameters will select the first or next valid ORACLE_SID from /etc/oratab.

	EOF
fi
