#!/bin/bash -p
# mocmd v1.5 2013-08-04, Finn Magnusson, finn.magnusson@ericsson.com
# Type "mocmd" for help.

###########################################################################################
# Pathes to files:
###########################################################################################
moshelldir=`dirname "$0"`
if [[ $moshelldir != /* ]] ; then moshelldir=`pwd`/$moshelldir ; fi
vobsinstallation=0
unamea=$(uname -a)
gawkext=""
gawklib=""
if [[ $unamea = [Ll][iI][nN][uU][xX]*x86_64* ]] ; then gawklib="lin64"   ; if [[ $vobsinstallation = 1 ]] ; then gawkext=".lin64" ; fi
elif [[ $unamea = [Ll][iI][nN][uU][xX]* ]]      ; then gawklib="linux"   ; if [[ $vobsinstallation = 1 ]] ; then gawkext=".linux" ; fi
elif [[ $unamea = SunOS*sparc* ]]               ; then gawklib="solaris" ; if [[ $vobsinstallation = 1 ]] ; then gawkext=".solaris" ; fi
elif [[ $unamea = SunOS* ]]                     ; then gawklib="sol86"   ; if [[ $vobsinstallation = 1 ]] ; then gawkext=".sol86" ; fi
else gawklib="cygwin" ; gawkext=".exe"
fi
gawkprog="gawk${gawkext}" 
gawk="$moshelldir/$gawkprog"
#special case where moshell has been installed on a linux 32 bit machine but should be run on linux 64 sharing the same file system
if [[ $unamea = [Ll][iI][nN][uU][xX]*x86_64* && $vobsinstallation != 1 && `file "$moshelldir/gawk"` = *32-bit* ]] ; then gawklib="linux" ; fi
filefunc="$moshelldir/commonjars/lib/${gawklib}/filefuncs"
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH:+${LD_LIBRARY_PATH}:}$moshelldir/commonjars/lib/${gawklib}
export LANG=C
export LC_ALL=C

logdir="$moshelldir/logfiles/logs_mocmd"
defLogDir=$moshelldir/commonjars/defLogDir.sh
temp_logdir=$($defLogDir mocmd)
if [[ -w $temp_logdir && -d $temp_logdir ]] ; then logdir=$temp_logdir ; fi
###########################################################################################

function print_usage()
{
cat <<EOF

Purpose: 
To generate an moshell/monode/mobatch command file from a parameter file.
The parameter file can be of two formats: 
 - baseline format as shown in moshell/examples/audit_files/baseline.txt
 - change_all format (ranos) 
 
Usage:  
mocmd <baseline file>|<change_all directory>
If a file is given as input, then baseline format is assumed.
If a directory is given as input, then change_all format is assumed.
For a baseline input, the output is given on the screen.
For a change_all input, the output given is a set of files in the result directory.

EOF
}

date_time=$(date +%y%m%d-%H%M)

baseline=0
change_all=0
case $# in
1)  if test -f "$1" ; then inputfile="$1" ; baseline=1 
    elif test -d "$1" ; then 
    	inputdir="$1" ; change_all=1 ;
    	inputbase=$(basename $inputdir) 
    	resultdir=${logdir}/${date_time}_${inputbase}
    else echo "File/Directory $1 not found. Exiting...." ; exit 1
    fi
    ;;    
*) print_usage ; exit 1
  ;;   
esac


$gawk -v inputfile="$inputfile" -v inputdir="$inputdir" -v baseline=$baseline -v change_all=$change_all -v resultdir=$resultdir -v vobsinstallation="$vobsinstallation" '
BEGIN{
	if (baseline == 1)
	{
		while (getline < inputfile)
		{
			gsub("\r","")
			if ((!/see CDR/)&&($1 !~ /^#/))
			{
				done=0
				gsub(/\(.*\)/,"")
				gsub(/^#.*$/,"")
				last=split($1,array,",")
				last=split(array[last],array,"=")
				motype=array[1]
				motype_list[motype]=1
				if ($1 ~ ",") mo=sprintf("%s$",$1)
				else if ($1 ~ "=") mo=sprintf("^%s$",$1)
				else    mo=sprintf("^%s=",$1)
				attribute=$2
				if (NF==3 && done == 0) 
					mo_att[mo,attribute]=$3
				else if ($3 ~ /\[[0-9]+\]/ && $4 == "=")
				{
					#this is an array
					mo_att[mo,attribute]=gensub(" ",",","g",gensub(/^.* = |[ \t]+$|/,"","g",$0))
				}
				else if (NF > 3)
				{
					for (i=3;i<=NF;i++)
					{
						mo_att[mo,attribute]=gensub(/^[ \t]+/,"","g",gensub($1,"","1",gensub($2,"","1",$0)))
					}
				}
				motype_comb[mo,attribute]=motype
				if (mo ~ /,/) command[mo,attribute]="lset"
				else      command[mo,attribute]="set"
			}
		}
		for (motype in motype_list)
			if (motype != "")
				motype_string=sprintf("%s|%s",motype_string,motype)
		printf("lt ^(%s)$\n",gensub(/^\|/,"","g",motype_string))
		for (motype in motype_list)
		{
			for (comb in mo_att)
			{
				if (motype_comb[comb]==motype)
				{
					split(comb,array,SUBSEP)
					printf("%-4s%6s%-30s%6s%-30s%6s%s\n",command[comb]," ",array[1]," ",array[2]," ",mo_att[comb])
				}
			}
		}
	}
	else if (change_all == 1)
	{
		#P3:    Equipment,1,Battery,batteryTestEndLimit,long,-456,vG.3.3,RBS3202,RBS
		#       NodeBFunction,0,NodeBFunction,toaeDch,long,170,vG.3.3,-,RBS
		#P2.1:	RncFunction,0,RncFunction,recordingStorageSize,60000,vD.6.3,-,RNC
		#       NodeBFunction,0,NodeBFunction,wideSearchTimer,150,vC.5.4,-,RBS
		#       Equipment,1,InterSubTimingCable,electricalDlDelay,44,vC.5.4,RBS3202,-
		system(sprintf("mkdir -p %s/baseline",resultdir))
		while (sprintf("ls -l %s",inputdir) |& getline) 
		{
			gsub("\r","")
			if ($1 ~ /^-rw/)
			{
				inputfile=sprintf("%s/%s",inputdir,$NF)
				while (getline < inputfile)
				{
					gsub("\r","")
					if (NF > 0 && $1 !~ /^#/)
					{
						last=split($0,array,",")
						motype=array[3]
						attribute=array[4]
						if (last<=8) #P2.1
						{
							value=array[5]  
							if (array[7]!="-") category=array[7]
							else category=array[8]
						}
						else #P3
						{
							value=array[6]
							if (array[8]!="-") category=array[8]
							else category=array[9]
						}
						moTypeList[category,motype]=motype
						categoryList[category]=category
						contents[category,sprintf("set ^%s= %s %s",motype,attribute,value)]=sprintf("set ^%s$ %s %s",motype,attribute,value)
					}
				}
				close(inputfile)
			}
		}
		close(sprintf("ls -l %s",inputdir))
		for (category in categoryList)
		{
			var=""
			cmdfile=sprintf("%s/%s.cmd",resultdir,category)
			baselinefile=sprintf("%s/baseline/%s.txt",resultdir,category)
			close(cmdfile)
			close(baselinefile)
			if (cmdfile ~ /\/(RBS.cmd|RNC.cmd)$/) printf("confbl\ngsg\n") > cmdfile
			printf("lt ^(") >> cmdfile
			for (comb in moTypeList)
			{
				split(comb,array,SUBSEP)
				if (array[1]==category)	var=sprintf("%s%s|",var,array[2])
			}
			printf("%s)$\n",gensub(/\|$/,"",1,var)) >> cmdfile
			for (comb in contents)
			{
				split(comb,array,SUBSEP)
				if (array[1]==category)
				{
					print array[2] >> cmdfile
					print gensub(/^set \^/,"",1,gensub("=","",1,array[2])) >> baselinefile
				}
			}
			close(cmdfile)
		}
		while (sprintf("ls -l %s",resultdir) |& getline) 
		{
			gsub("\r","")
			if ($1 ~ /^-rw/)
			{
				if ($NF ~ /^RBS3[0-9]+.cmd$/)
				{
					rbs_filename=$NF
					rbsFileList[sprintf("%s/%s",resultdir,rbs_filename)]=1
					if (getNodeTypePrinted !=1) 
					{
						printf("get 0 productname > $productname\n") >> sprintf("%s/RBS.cmd",resultdir)
						getNodeTypePrinted = 1
					}	
					printf("if $productname = %s\n",gensub(/.cmd/,"",1,rbs_filename)) >> sprintf("%s/RBS.cmd",resultdir)
					while (getline < sprintf("%s/%s",resultdir,rbs_filename))
					{
						print $0 >> sprintf("%s/RBS.cmd",resultdir)
					}
					close(sprintf("%s/%s",resultdir,rbs_filename))
					print "fi" >> sprintf("%s/RBS.cmd",resultdir)
					#system(sprintf("rm %s/%s",resultdir,$NF))
				}
			}
		}
		close(sprintf("ls -l %s",resultdir))
		for (file in rbsFileList) system("rm "file)
		printf("Results saved in %s\n",resultdir)
	}					
}

'
