#!/bin/bash
#

echo "CHECKING tnsnames.ora FOR tns_alias=${1} .."
tns_alias=$( grep -i "^$1\.." tnsnames.ora )

if [[ ! -z "${tns_alias}" ]] ; then
  start=$( grep -in "^$1\.." tnsnames.ora | awk -F":" '{ print $1 }' )
  end=$(( start + 25 ))
  ##echo "start=$start | end=$end"
  sed -n "${start},${end}p" tnsnames.ora > /tmp/tnsnames.ora.tmp
  cat /dev/null > /tmp/tnsnames.ora.alias
  switch=0
  ##while read -r line
  while IFS= read -r line # retain indentation/white space
  do
    case $switch in
      0 )
        ## This is the TNS alias, the first line
        echo "$line" >> /tmp/tnsnames.ora.alias
        switch=1
        ;;
      1 ) 
        if [[ ! -z $( echo $line | grep "=$" ) ]]  && [[ ! -z $( echo $line | grep -i "(" ) ]] ; then
          echo "$line" >> /tmp/tnsnames.ora.alias
        else
          if [[ ! -z $( echo $line | grep "=$" ) ]] ; then
            break
          else
            echo "$line" >> /tmp/tnsnames.ora.alias
          fi
        fi
        ;;
    esac
  done < /tmp/tnsnames.ora.tmp
  echo
  ls /tmp/tnsnames*
  echo
  echo "## FOUND TNS alias entry ( \$1=$1 | tns_alias=[$tns_alias] ) = /tmp/tnsnames.ora.alias"
  cat /tmp/tnsnames.ora.alias
  echo
  echo "## Host BELOW:"
  echo "$( cat /tmp/tnsnames.ora.alias | tr [:upper:] [:lower:] | sed "s# *##g" | grep -i "(host" | awk -F"host=" '{ print $2 }' | awk -F")" '{ print $1 }' )"
  echo "## Port BELOW:"
  echo "$( cat /tmp/tnsnames.ora.alias | tr [:upper:] [:lower:] | sed "s# *##g" | grep -i "(port" | awk -F"port=" '{ print $2 }' | awk -F")" '{ print $1 }' )" 
  echo "## SERVICE BELOW:"
  echo "$( cat /tmp/tnsnames.ora.alias | tr [:upper:] [:lower:] | sed "s# *##g" | grep -i "(service_name" | awk -F"service_name=" '{ print $2 }' | awk -F")" '{ print $1 }' )" 
else
  echo "## tns_alias = [$1] NOT FOUND"
fi

