#!/bin/sh
#########################################################################
# Script used to view current local domain
# Usage: idc-localdomainView
# TBD: Remove echo statements. Retaining expecting future changes
# TDB: Run from OSCARS_HOME location. Right now run from OSCARS_DIST
#########################################################################

#check if $OSCARS_HOME is set
REPO_PATH=""
if [ -n "$OSCARS_HOME" ]; then
	REPO_PATH=OSCARS_HOME
else
	echo "ERROR: OSCARS_HOME is not set. Re-run this script after setting OSCARS_HOME."
	exit 1
fi

#Search topology file and get the values

## define context to be production, since the local Domain is defined in just one place
CONTEXT=PRODUCTION
#Config=$(sh $OSCARS_DIST/tools/bin/parseManifest.sh Utils $CONTEXT utils) # | sed "s/'//g")
Config=$(sh $OSCARS_DIST/tools/bin/parseManifest.sh Utils Utils $CONTEXT | sed "s/'//g")
if [ -z $Config ]; then
      echo "The manifest file is not found/or is invalid. Have you run the bin/copyTemplates.sh and/or bin/exportconfig commands?"
      exit 1
fi
Service=$(echo $Config | awk -F/ '$1~//{print $2}')
Conf=$(echo $Config | awk -F/ '$1~//{print $3}')
Yaml=$(echo $Config | awk -F/ '$1~//{print $4}' | sed "s/'//g")
if [ "$Conf" == "conf" ]; then
	configFile=$OSCARS_HOME/$Service/$Conf/$Yaml
elif [ "$Conf" == "config" ]; then
	configFile=$OSCARS_DIST/$Service/$Conf/$Yaml
fi
#echo "The config file location is $configFile"

if [ -z $configFile ] || [ ! -f $configFile ]; then
	echo "The configuration file is not found. You may have to:"
	echo "  1. Rerun this script after running copyTemplates.sh and/or bin/exportconfig"
	echo "  2. alternatively, look up the local domain used in $OSCARS_HOME/Utils/conf/config.yaml (if present)"
	exit 1
fi

SVCFND=0
CONTFND=0
LOCALDOMAIN=localDomain #Local domain indicator string

#TBD manifest location
while read i; 
do
	Line=$(echo $i)
	#trim
	Line=$(echo $Line | sed 's/^ *\(.*\) *$/\1/')
	iscomment=$(echo $Line | awk '/^#/ {print "comment"}')
        if [ "$iscomment" == "comment" ]; then
                #echo "comment found"
                continue;
	fi
	if [ $CONTFND -eq 0 ]; then
		localDmId=$(echo $Line | awk -F: '$1~/'$LOCALDOMAIN'/{print "FOUND"}')
		if [ "$localDmId" == "FOUND" ]; then
			CONTFND=1
		fi
	elif [ $CONTFND -eq 1 ]; then
		CON2=$(echo $Line | awk -F: '$1~/id/{print "FOUND"}')
        	if [ "$CON2" == "FOUND" ]; then
			localDomain=$(echo $Line | awk -F: '$1~/id/{print $2}' | sed "s/'//g")
			CONTFND=0
		fi
		echo "The local Domain currently being used:$localDomain"
  	fi
done<$configFile
