#!/usr/bin/bash
# Script: doconservice.sh
# Author: Theodore Zacharia
# Version: 1.0 15/11/2013 - Finally extracted this out of doflashback.sh
#
# Utility script manage connector services for a clustered Oracle DB
# The main modes of operation are:
# * list     - which lists the services
# * status   - status of the service
# * start    - start the service
# * stop     - stop the service
#
# Addtionally
#
# * or | mis - specify which services to stop or start
#

# ***** Mainline

while getopts s: AOPT
do
case $AOPT in
        s) export ORAENV_ASK=NO;export ORACLE_SID=$OPTARG;. oraenv ;;
esac
done

shift $((OPTIND-1))

echo "***** IMPORTANT *****"
echo "Ensure you have run . oraenv and set your DB correctly"
echo " "
if [[ $ORACLE_SID == "" || $ORACLE_SID == "oracle" ]]
then
        echo "**** WARNING, it looks like you have not set the SID"
        echo "     continuing, but it probably will not work :( "
fi


if (( $# < 1 ))
then
	echo "usage: $0 [-s SID] list|[status|start|stop <or|mis>]"
	echo "-s SID   - allows you to set the ORACLE SID"
	echo "The full set of options are:"
	echo "list     - list the con services on the machine"
	echo "status   - status of the specified service"
	echo "start    - start the specified service"
	echo "stop     - stop the specified service"
	exit
fi

MNAME="$2"

# get host details
HOSTNAME=`uname -n`
HOSITID=`uname -n | awk '{print substr($0, length, 1)}'`
ORACLE_CLUSTER=${ORACLE_SID%1}

# workout name of connector service based on where we are and user request
# the pattern part of this test must NOT be quoted
if [[ $HOSTNAME = sse* ]]
then
	THISENV="s"
else
	THISENV="l"
fi

# NOTE: This workds out a service name based on LSE/SSE, when this DB service changes need to change it below
if [[ "$2" == "mis" ]]
then
	CONSERVICENAME="${MNAME}con"
else
	CONSERVICENAME="${THISENV}2${MNAME}con"
fi

if [[ $1 == "list" ]]
then
	echo "following connector services found for cluster $ORACLE_CLUSTER:"
	srvctl status service -d $ORACLE_CLUSTER 
elif [[ $1 == "status" ]]
then
	echo "status of $CONSERVICENAME for cluster $ORACLE_CLUSTER:"
	srvctl status service -d $ORACLE_CLUSTER -s $CONSERVICENAME
elif [[ $1 == "start" ]]
then
	echo "starting the $CONSERVICENAME service on cluster $ORACLE_CLUSTER"
	srvctl start service -d $ORACLE_CLUSTER -s $CONSERVICENAME
elif [[ $1 == "stop" ]]
then
	echo "stopping the $CONSERVICENAME service on cluster $ORACLE_CLUSTER"
	srvctl stop service -d $ORACLE_CLUSTER -s $CONSERVICENAME
else
	echo "unknown command"
fi