#!/bin/bash -p
# netcheck v1.4 2013-08-04, Finn Magnusson, finn.magnusson@ericsson.com
# Type "netcheck" on its own 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_netcheck"
defLogDir=$moshelldir/commonjars/defLogDir.sh
temp_logdir=$($defLogDir netcheck)
if [[ -w $temp_logdir && -d $temp_logdir ]] ; then logdir=$temp_logdir ; fi
###########################################################################################


function print_usage()
{
cat <<EOF
Command Syntax:
***************  
1) To compare logs against a reference file:
	netcheck <Ref-File> <LogDirectory>|<Logfile>
2) To compare a set of logs with each other (eg before and after an upgrade):
	netcheck -b <LogDirectory-Before> -a <LogDirectory-After>
3) To generate a set of telbatch command files needed for changing password on the node
	netcheck -p <Ipdatabase> <sitefile>	

Ref-File: See example in moshell/examples/netcheck_files/RefList.txt
*********
	
Logfiles (moshell dumps):
*************************
	MoShell dumps should be taken with mobatch or monode, using command:
	       monode       <ip_address> <cmdfile>  (for dumping one node)
	   OR: mobatch      <sitefile>   <cmdfile>  (for dumping several nodes in parallel)
	The command file should be like the one in moshell/examples/mobatch_cmdfiles/netcheck_xxx.mos
	Make sure that the nodes passwords are specified in the ipdatabase file.

Example:
********
  >> netcheck ./p3_upgrade/RefList_rbs.txt ./moshell_logfiles/logs_mobatch/030630-1830_allRbs/
  >> netcheck -b ./moshell_logfiles/logs_mobatch/031201-1400_allRbs/ -a ./moshell_logfiles/logs_mobatch/031201-1715_allRbs/
  		
EOF
}

function netcheck()
{
$gawk -v input_file=$inputfile -v input_file_name=$inputbase -v check_hw=$check_hw -v check_disk=$check_disk -v reffile=$reffile -v resultdir=${resultdir} -v inputtype=$input -v inputdir=$inputdir -v vobsinstallation="$vobsinstallation" '
BEGIN{
	printf("Parsing Reference File %s ...",reffile)
	parse_ref(reffile,hwRef)
	printf("Done.\n")

	lockcmdDir=sprintf("%s/mobatch_cmdfiles/lock",resultdir)
	unlockcmdDir=sprintf("%s/mobatch_cmdfiles/unlock",resultdir)
	system(sprintf("mkdir -p %s",lockcmdDir))
	system(sprintf("mkdir -p %s",unlockcmdDir))

	hwResFile=sprintf("%s/hwCheck.txt",resultdir)
	printf("#############################################################################################\n\
List of boards found in the nodes but not in the reference file:\n\
#############################################################################################\n") > hwResFile
	redLedFile=sprintf("%s/redLed.txt",resultdir)
	printf("#############################################################################################\n\
List of boards with the red led on:\n\
#############################################################################################\n") > redLedFile
	upFile=sprintf("%s/unallowedUP.txt",resultdir)
	printf("#############################################################################################\n\
List of nodes with unallowed UP:\n\
#############################################################################################\n") > upFile
	ipFile=sprintf("%s/missingIp.txt",resultdir)
	printf("#############################################################################################\n\
List of nodes with missing Ip MOs (Only applies to RBS):\n\
#############################################################################################\n") > ipFile
	unlockedFile=sprintf("%s/unlockedDisabled.txt",resultdir)
	printf("#############################################################################################\n\
List of nodes containing Unlocked-Disabled MOs:\n\
#############################################################################################\n") > unlockedFile
	alFile=sprintf("%s/unacceptableAlarms.txt",resultdir)
	printf("#############################################################################################\n\
List of nodes containing unacceptable alarms:\n\
#############################################################################################\n") > alFile
	disFile=sprintf("%s/unacceptableDisabled.txt",resultdir)
	printf("#############################################################################################\n\
List of nodes containing disabled MOs:\n\
#############################################################################################\n") > disFile
	tmaFile=sprintf("%s/noTma.txt",resultdir)
	printf("#############################################################################################\n\
List of nodes not using TMA:\n\
#############################################################################################\n") > tmaFile
	restartFile=sprintf("%s/abnormalRestarts.txt",resultdir)
	printf("#############################################################################################\n\
List of nodes containing abnormal board restarts:\n\
#############################################################################################\n") > restartFile
	errorFile=sprintf("%s/unallowedErrors.txt",resultdir)
	printf("#############################################################################################\n\
List of nodes containing unallowed errors in T&E log:\n\
#############################################################################################\n") > errorFile
	cellFile=sprintf("%s/unavailableCells.txt",resultdir)
	printf("#############################################################################################\n\
List of unavailable cells:\n\
RNC         MOD  IUBLINK       CELLNAME          SECT1  SECT2  SECT3  CD12\n\
#############################################################################################\n") > cellFile
	noContactFile=sprintf("%s/noContact.txt",resultdir)
	printf("#############################################################################################\n\
List of unreachable sites:\n\
#############################################################################################\n") > noContactFile
	

	diskSpaceFile=sprintf("%s/diskSpace.txt",resultdir)
	printf("#############################################################################################\n\
List of disks with insufficient space:\n") > diskSpaceFile
	diskList["c"]=diskList["d"]=1
	for (disk in diskList)
	{
		if (reqSpace[disk] !="") 
		{
			printf("%s < %sM ",disk,reqSpace[disk]) >> diskSpaceFile
			if (reqPart[disk]  !="") printf("and %s < %s% ",disk,reqPart[disk]) >> diskSpaceFile
		}
		else if (reqPart[disk] != "") printf("%s < %s%",disk,reqPart[disk]) >> diskSpaceFile
		print "" >> diskSpaceFile
	}
	printf("#############################################################################################\n") >> diskSpaceFile

	if (inputtype=="file") 
	{
		inputfile[1]=input_file
		inputfilename[1]=input_file_name
		sitename[1]=gensub(/\.log$/,"","1",inputfilename[1])
		nr_of_files=1
	}
	else
	{
		
		#-rw-r--r--    1 eric     eric        30449 May 15 16:25 6000010.log
		while (sprintf("ls -l %s",inputdir) |& getline) 
		{
			gsub("\r","")
			if ($1 ~ /^-rw/)
			{
				i++
				inputfile[i]=sprintf("%s/%s",inputdir,$NF)
				inputfilename[i]=$NF
				sitename[i]=gensub(/\.log$/,"","g",$NF)
			}
		}
		close(sprintf("ls -l %s",inputdir))
		nr_of_files=i
	}		
	for (i=1;i<=nr_of_files;i++)
	{	
		printf("Checking input file %s ...",inputfile[i])
		parse_file(inputfile[i],hwList,sitename[i],freeSpace,freePart)
		compareHw(hwResFile,sitename[i],hwRef,hwList)
		checkDisk(diskSpaceFile,sitename[i],freeSpace,freePart)
		printf("Done.\n\n")
	}


	printf("Result files are saved in %s\n",resultdir)
}

function parse_ref(file,hwRef,  array,valid_ref_file,field,faulty_ref)
{
	valid_ref_file["HW"]=0
	valid_ref_file["Disk"]=0
	valid_ref_file["UP"]=0
	valid_ref_file["Alarms"]=0
	valid_ref_file["DisabledMOs"]=0
	valid_ref_file["Errors"]=0	
	while (getline < file)
	{
		gsub("\r","")
		if (tolower($1) == "<supportedhw>")
		{
			valid_ref_file["HW"]=1
			while (tolower($1) != "</supportedhw>")
			{
				getline < file
				gsub("\r","")
				gsub(" ","")
				if (NF>2 && $1 !~ /^#/) hwRef[$2,$3]=1
			}
		}		
		if (tolower($1) == "<freediskspace>")
		{
			valid_ref_file["Disk"]=1
			while (tolower($1) != "</freediskspace>")
			{
				getline < file
				gsub("\r","")
				gsub(" ","")
				if ($1 !~ /^#/)
				{
					split($1,array,":")
					if (tolower(array[1]) ~ /^(c|d)$/)
					{
						if ($1 ~ "M") reqSpace[tolower(array[1])]=gensub(/[A-Z]/,"","g",array[2])+0
						else if ($1 ~ "%") reqPart[tolower(array[1])]=gensub("%","","g",array[2])+0
					}
				}
			}
		}
		if (tolower($1) == "<allowedcurrentups>")
		{
			valid_ref_file["UP"]=1
			while (tolower($1) != "</allowedcurrentups>")
			{
				getline < file
				gsub("\r","")
				if ($1 !~ /^#/) allowedUP[$1]=$1
			}
		}
		if (tolower($1) == "<allowedalarms>")
		{
			valid_ref_file["Alarms"]=1
			while (tolower($1) != "</allowedalarms>")
			{
				getline < file
				gsub("\r","")
				gsub(/[ ]+/," ")
				allowedAlarms[$0]=$0
			}
		}
		if (tolower($1) == "<alloweddisabled>")
		{
			valid_ref_file["DisabledMOs"]=1
			while (tolower($1) != "</alloweddisabled>")
			{
				getline < file
				gsub("\r","")
				gsub(/[Mm]anaged[Ee]lement=1,/,"")
				allowedDisabled[$1]=$1
			}
		}
		if (tolower($1) == "<allowederrors>")
		{
			valid_ref_file["Errors"]=1
			while (tolower($1) != "</allowederrors>")
			{
				getline < file
				gsub("\r","")				
				allowedErrors[$0]=$0
			}
		}
	}
	close(file)
	for (field in valid_ref_file){ if (valid_ref_file[field]==0) faulty_ref=1 }
	if (faulty_ref==1) printf("\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\
\33[1m\33[31m!!!!! Missing following fields in reference file: \33[0m")
	for (field in valid_ref_file) { if (valid_ref_file[field]==0) printf field" " }
	if (faulty_ref==1) print "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
}
	
function compareHw(resultfile,site,hwRef,hwList,  ok,array,comb)
{
	#for (comb in hwList)
	#{
	#	split(comb,array,SUBSEP)
	#	print array[1],array[2]
	#}
	#for (comb in hwRef)
	#{
	#	split(comb,array,SUBSEP)
	#	print array[1],array[2]
	#}
	for(comb in hwList)
	{
		ok=0
		split(comb,arraylist,SUBSEP)
		for (comb1 in hwRef)
		{
			split(comb1,arrayref,SUBSEP)
			if (arraylist[1]==arrayref[1] && arraylist[2] >= arrayref[2])
			{
				ok=1
				#print comb,comb1
				break
			}
		}
		if (ok==0) 
		{
			split(comb,array,SUBSEP)
			printf("%-10s  %s: %s,%s\n",site,hwList[comb],array[1],array[2]) >> resultfile
		}
	}
	print "" >> resultfile
}
function checkDisk(resultfile,site,freeSpace,freePart,  array,comb,nrOfDisks)
{
	#for (comb in reqSpace) print comb,reqSpace[comb]
	#for (comb in reqPart) print comb,reqPart[comb]
	#for (comb in freeSpace) print comb,freeSpace[comb]
	#for (comb in freePart)  print comb,freePart[comb]
	for (comb in freeSpace) nrOfDisks++
	for(comb in freeSpace)
	{			
		if (comb == "c")
		{
			if (freeSpace["c"] < reqSpace["c"])
				printf("%-10s  %5s:  %sM\n",site,"c",freeSpace[comb]) >> resultfile
		}
		else
		{				
			split(comb,array,SUBSEP)
			if (freeSpace[comb] < reqSpace["d"])
			{
				if (nrOfDisks==2) printf("%-10s  %5s:  %sM\n",site,array[2],freeSpace[comb]) >> resultfile
				else printf("%-10s  %4s%s:  %sM\n",site,array[1],array[2],freeSpace[comb]) >> resultfile
			}
		}
	}
	for(comb in freePart)
	{			
		if (comb == "c")
		{
			if (freePart["c"] < reqPart["c"])
				printf("%-10s  %5s:  %s%\n",site,"c",freePart[comb]) >> resultfile
		}
		else
		{				
			split(comb,array,SUBSEP)
			if (freePart[comb] < reqPart["d"])
			{
				if (nrOfDisks==2) printf("%-10s  %5s:  %s%\n",site,array[2],freePart[comb]) >> resultfile
				else printf("%-10s  %4s%s:  %s%\n",site,array[1],array[2],freePart[comb]) >> resultfile
			}
		}
	}
	print "" >> resultfile
}		
function parse_file(file,hwList,site,freeSpace,freePart,  \
hwNumber,hwRevision,array,last,upFound,currentUP,up,ip,eth,routingtable,redLedFound,\
unlockedMOs,al,foundAl,alarm,foundAl1,mo,foundDis,foundDis1,tma,unlockedMoList,\
unlockedMoTypeList,motype,var,restartFound,errorlist,errorFound,error,i,lockedMoList)
{
	delete hwList ; delete freeSpace ; delete freePart
	lockcmdfile=sprintf("%s/%s.cmd",lockcmdDir,site)
	unlockcmdfile=sprintf("%s/%s.cmd",unlockcmdDir,site)
	chpwfile=sprintf("%s/%s.cmd",chpwDir,site)
	while (getline < file)
	{
		gsub("\r","")
		#i++
		if (/Checking ip contact...Not OK/) printf("%s\n",site) >> noContactFile
		if ($1 ~ /^[0-9]+$/ && ($2 ~ /^([0-9]|[1-2][0-9])$/ && $3 !~ /\(/ && $0 !~ /CXC/ && $NF !~ /^[0-9]+$/)\
				    || ($0 ~ /BACKPLANE/) )
		{
			if ($0 ~ /BACKPLANE/) hwPosition=sprintf("%02s",$1)
			else hwPosition=sprintf("%02s%02s",$1,$2)
			if ($0 ~ /\x27/)
			{
				#  0    1  port_0_dev_14  FAN UNIT     steady  off     off     BKV 301 487/1  R2A   20021025   TH4C703561 
				hwType=gensub(/\x27/,"","g",$4)
				split($0,array,/\x27/)
				hwNumber=array[4]
				hwRevision=array[6]
				split(array[3],array," ")
				redLed=array[3]	
			}
			else
			{
				#  0   20  HUB MP     ON      16HZ    OFF     ROJ 119 2106/2   R4D     02W25 T011756848  +27C Active
				#  0   15  RAX        ON      OFF     OFF     ROJ 119 2071/3   R2A     02W47 A534211345      
				#  1    4  TRX 3.3    ON      16HZ    OFF     ROJ 119 2125/3   R4F     02W47 A534213491
				#  0  ROJ 605 107/1       R5A   BACKPLANE   02W49     T821198026
				#  1  ROJ 605 108/1       R4A   BACKPLANE   02W39     T821188912
				if ($0 ~ /BACKPLANE/) hwType="BACKPLANE"
				else hwType=$3
				match($0,/(ROJ|KRY|KRC)[ 0-9\/]+/)
				hwNumber=substr($0,RSTART,RLENGTH)
				if ($NF ~ /^.[0-9]+C$/) hwRevision=$(NF-3)
				else if ($NF ~ /^(Active|Standby)/) hwRevision=$(NF-4)
				else if ($0 ~ /BACKPLANE/) hwRevision=$(NF-3)
				else hwRevision=$(NF-2)
				#Red Led
				last=split(gensub(/(ROJ|KRY|KRC).*$/,"","g",$0),array," ")
				redLed=array[last]
			}
			gsub(/ /,"",hwNumber)
			#match(hwRevision,/[RP][0-9]+/)
			#hwRevision=substr(hwRevision,RSTART,RLENGTH)
			hwList[hwNumber,hwRevision,hwPosition]=sprintf("%s %-10s",hwPosition,"("hwType")")
			if (hwNumber == "" || hwRevision=="") delete hwList[hwNumber,hwRevision]
			else if (tolower(redLed) !~ "off")
			{
				printf("%-10s  %s  %-10s\n",site,hwPosition,"("hwType")") >> redLedFile
				redLedFound=1
			}
			#print i,hwNumber,hwRevision,"x"
		}
		if ($1 ~ /^[0-9][0-9][0-9][0-9]+:$/ && $6 ~ /^[0-9]+M/)
		{
			if ($2 ~ /^\/c/ ) 
			{
				freeSpace["c"]=gensub("M","","g",$6)+0
				freePart["c"]=gensub("%","","g",$7)+0
			}
			else if ($2 ~ /^\/d/) 
			{
				freeSpace[gensub(":","","g",$1),"d"]=gensub("M","","g",$6)+0
				freePart[gensub(":","","g",$1),"d"]=gensub("%","","g",$7)+0
			}
		}
		if ($0 ~ /^Current UpgradePkg:/) 
		{
			currentUP=$NF
			upFound=0
			for (up in allowedUP) if (up == currentUP) upFound=1
			if (upFound==0) printf("%-10s: %s\n",site,currentUP) >> upFile
		}
		if (/IpSystem=1,Ip=/) ip=1
		if (/IpRoutingTable=/) routingtable=1
		if (/EthernetLink=/) eth=1
		if (/,(AscDevice|TmaDevice|ExternalTma).*=/)  tma=1 
		if (/1 .UNLOCKED.  0 .DISABLED./)
		{
			printf("%-10s: %s\n",site,$NF) >> unlockedFile
			unlockedMoList[$NF]=$NF
			unlockedMOs=1
		}
		if ($1 ~ /^(Maj|Min|Crit|Warn|Cleared|\?)$/)
		{
			alarm=gensub(/[ ]+/," ","g",$0)
			foundAl=0
			for (al in allowedAlarms) if (allowedAlarms[al] == alarm) foundAl=1
			if (foundAl==0) 
			{
				printf("%-10s: %s\n",site,$0) >> alFile
				foundAl1=1
			}
		}
		if (/0 .LOCKED./) lockedMoList[$NF] = $NF
		if (/0 .DISABLED. /)
		{
			foundDis=0
			for (mo in allowedDisabled) if (allowedDisabled[mo] == $NF) foundDis=1
			for (mo in locked) if (lockedMoList[mo] == $NF || "x"$NF ~ "x"lockedMoList[mo]",") foundDis=1
			if (foundDis == 0)
			{
				printf("%-10s  %s\n",site,$NF) >> disFile
				foundDis1=1
			}
		}
		if ($2 ~ /^[0-9][0-9]-[0-9][0-9]-[0-9][0-9]$/ && $3 ~ /^[0-9][0-9]:[0-9][0-9]:[0-9][0-9]$/ && $0 ~ / 0x/)
		{
			printf("%-10s  %s\n",site,$0) >> restartFile
			restartFound=1
		}
		if (/ERROR:/)
		{
			error=gensub(/^.*\[200.-..-.. ..:..:......\] |\33\[0m/,"","1",$0) 
			for (allowederror in allowedErrors)
			{
				if (error ~ allowederror) error=""
			}
			if (error != "") 
			{
				errorFound=1
				errorlist[error]=error
			}
		}
		if ($NF ~ /^[L01][L01][L01]+$/ && $(NF-1) ~ /^[L01][L01][L01]+$/)
		{
			faultySite=0
			for (i=4; i<=NF;i++)
			{
				if ($i ~ "0") faultySite =1
			}
			if (faultySite == 1) printf("%-10s  %s\n",site,$0) >> cellFile
		}
	}
	close(file)
	if (faultySite != "") print "" >> cellFile
	if (restartFound != "") print "" >> restartFile
	if (redLedFound != "") print "" >> redLedFile
	if (unlockedMOs != "") print "" >> unlockedFile
	if (foundAl1 != "") print "" >> alFile
	if (foundDis1 !="") print "" >> disFile
	if (tma != 1) printf("%s\n",site) >> tmaFile
	if (ip !=1 || routingtable !=1 || eth !=1) 
	{
		printf("%-10s: ",site) >> ipFile
		if (ip !=1) printf("Ip ") >> ipFile
		if (eth !=1) printf("EthernetLink ") >> ipFile
		if (routingtable !=1) printf("IpRoutingTable") >> ipFile
		print "" >> ipFile
	}
	if (unlockedMOs==1)
	{
		for (mo in unlockedMoList)
		{
			last=split(mo,array,",")
			split(array[last],array,"=")
			unlockedMoTypeList[array[1]]=array[1]
		}
		for (motype in unlockedMoTypeList) var=sprintf("%s%s|",var,motype)
		printf("lt ^(%s)$\n",gensub(/\|$/,"","1",var)) > lockcmdfile 
		printf("lt ^(%s)$\n",gensub(/\|$/,"","1",var)) > unlockcmdfile 
		for (mo in unlockedMoList)  
		{
			printf("lbl %s$\n",mo) >> lockcmdfile
			printf("ldeb %s$\n",mo) >> unlockcmdfile
		}
	}
	if (errorFound == 1) 
	{
		for (error in errorlist)
		{
			printf("%-10s  %s\n",site,error) >> errorFile
		}
		print "" >> errorFile
	}
	close(hwResFile)
	close(diskSpaceFile)
	close(redLedFile)
	close(upFile)     
	close(ipFile)
	close(unlockedFile)
	close(alFile)    
	close(disFile)    
	close(tmaFile)
	close(restartFile)
	close(errorFile)
	close(cellFile)
	close(noContactFile)
}
'
}

function diffcheck()
{
$gawk -v beforedir="$beforedir" -v afterdir="$afterdir" -v resultdir="$resultdir" '
BEGIN{
	alFile=sprintf("%s/newAlarms.txt",resultdir)
	printf("#############################################################################################\n\
Following alarms have appeared in the postcheck:\n\
#############################################################################################\n") > alFile
	disFile=sprintf("%s/newDisabled.txt",resultdir)
	printf("#############################################################################################\n\
Following disabled MOs have appeared in the postcheck:\n\
#############################################################################################\n") > disFile
	cellFile=sprintf("%s/newCellsDown.txt",resultdir)
	printf("#############################################################################################\n\
Following disabled Cells have appeared in the postcheck:\n\
RNC         MOD  IUBLINK       CELLNAME          SECT1  SECT2  SECT3  CD12\n\
#############################################################################################\n") > cellFile
	alFileLess=sprintf("%s/lessAlarms.txt",resultdir)
	printf("#############################################################################################\n\
Following alarms have disappeared from the postcheck:\n\
#############################################################################################\n") > alFileLess
	disFileLess=sprintf("%s/lessDisabled.txt",resultdir)
	printf("#############################################################################################\n\
Following disabled MOs have disappeared from the postcheck:\n\
#############################################################################################\n") > disFileLess
	cellFileLess=sprintf("%s/lessCellsDown.txt",resultdir)
	printf("#############################################################################################\n\
Following disabled Cells have disappeared from the postcheck:\n\
RNC         MOD  IUBLINK       CELLNAME          SECT1  SECT2  SECT3  CD12\n\
#############################################################################################\n") > cellFileLess
	while (sprintf("ls -l %s",beforedir) |& getline) 
	{
		gsub("\r","")
		if ($1 ~ /^-rw/)
		{
			i++
			beforefile[i]=sprintf("%s/%s",beforedir,$NF)
			beforefilename[i]=$NF
			beforesite[i]=gensub(/\..*$/,"","g",$NF)
		}
	}
	close(sprintf("ls -l %s",beforedir))
	nr_of_beforefiles=i ; i=0
	while (sprintf("ls -l %s",afterdir) |& getline) 
	{
		gsub("\r","")
		if ($1 ~ /^-rw/)
		{
			i++
			afterfile[i]=sprintf("%s/%s",afterdir,$NF)
			afterfilename[i]=$NF
			aftersite[i]=gensub(/\..*$/,"","g",$NF)
		}
	}
	close(sprintf("ls -l %s",afterdir))
	nr_of_afterfiles=i ; i=0
	for (i=0;i<=nr_of_afterfiles;i++)
	{
		beforeFile=""
		for (j=0;j<=nr_of_beforefiles;j++)
		{
			if (afterfilename[i]==beforefilename[j])
			{
				beforeFile=beforefile[j]
				break
			}
		}
		if (beforeFile != "")
		{
			delete disAfter ; delete disBefore ; delete alAfter ; delete alBefore ; delete downAfter ; delete downBefore
			foundAl=foundDis=foundAlLess=foundDisLess=foundDown=foundDownLess=0 
			alcmdAft=alcmdBef=stcmdAft=stcmdBef=strcmdAft=strcmdBef=0
			printf("Comparing pre- and post-check for site %s...",aftersite[i])
			while (getline < afterfile[i])
			{
				gsub("\r","")
				if (/Proxy *Adm.*State *Op.*State *MO/) stcmdAft=1
				if (/Sever *Specific Problem *Cause *Mo/) alcmdAft=1
				if (/0 .DISABLED. /) disAfter[$NF]=$NF
				if ($1 ~ /^(Maj|Min|Crit|Warn|Cleared|\?)$/) alAfter[$0]=$0
				if (/MOD *IUBLINK *CELLNAME *SECT1 *SECT2 *SECT3 *CD12/) strcmdAft=1
				if ($NF ~ /^[L01][L01][L01]+$/ && $(NF-1) ~ /^[L01][L01][L01]+$/)
				{
					faultySite=0
					for (k=4; k<=NF;k++)
					{
						if ($k ~ "0") faultySite =1
					}
					if (faultySite == 1) downAfter[$0]=$0
				}
				
			}
			close(afterfile[i])
			while (getline < beforeFile)
			{
				gsub("\r","")
				if (/Proxy *Adm.*State *Op.*State *MO/) stcmdBef=1
				if (/Sever *Specific Problem *Cause *Mo/) alcmdBef=1
				if (/0 .DISABLED. /) disBefore[$NF]=$NF
				if ($1 ~ /^(Maj|Min|Crit|Warn|Cleared|\?)$/) alBefore[$0]=$0
				if (/MOD *IUBLINK *CELLNAME *SECT1 *SECT2 *SECT3 *CD12/) strcmdBef=1
				if ($NF ~ /^[L01][L01][L01]+$/ && $(NF-1) ~ /^[L01][L01][L01]+$/)
				{
					faultySite=0
					for (k=4; k<=NF;k++)
					{
						if ($k ~ "0") faultySite =1
					}
					if (faultySite == 1) downBefore[$0]=$0
				}
			}
			close(beforefile[i])
			if (alcmdAft==1 && alcmdBef==1)
			{
				for (ala in alAfter)
					for (alb in alBefore)
						if (alAfter[ala]==alBefore[alb]) { delete alAfter[ala] ; delete alBefore[alb] }
				for (ala in alAfter)
				{
					if (alAfter[ala] !="")
					{
						printf("%-10s: %s\n",aftersite[i],alAfter[ala]) >> alFile
						foundAl=1
					}
				}
				for (ala in alBefore)
				{
					if (alBefore[ala] !="")
					{
						printf("%-10s: %s\n",aftersite[i],alBefore[ala]) >> alFileLess
						foundAlLess=1
					}
				}
				if (foundAl==1) print "" >> alFile
				if (foundAlLess==1) print "" >> alFileLess
			}
			else 
			{
				if (alcmdAft==0 && alcmdBef==0)	output=sprintf("%-10s: alarm printout missing in pre- and post-check!!!\n",aftersite[i]) 
				else if (alcmdBef==0) output=sprintf("%-10s: alarm printout missing in precheck!!!\n",aftersite[i])
				else if (alcmdAft==0) output=sprintf("%-10s: alarm printout missing in postcheck!!!\n",aftersite[i])
				print output >> alFile
				print output >> alFileLess
			}
			if (stcmdAft==1 && stcmdBef==1)
			{
				for (disa in disAfter)
					for (disb in disBefore)
						if (disAfter[disa]==disBefore[disb]) { delete disAfter[disa] ; delete disBefore[disb] }
				for (disa in disAfter)
				{
					if (disAfter[disa] != "")
					{
						printf("%-10s: %s\n",aftersite[i],disAfter[disa]) >> disFile
						foundDis=1
					}
				}
				for (disa in disBefore)
				{
					if (disBefore[disa] != "")
					{
						printf("%-10s: %s\n",aftersite[i],disBefore[disa]) >> disFileLess
						foundDisLess=1
					}
				}			
				if (foundDis==1) print "" >> disFile
				if (foundDisLess==1) print "" >> disFileLess
			}
			else 
			{
				if (stcmdAft==0 && stcmdBef==0)	output=sprintf("%-10s: state printout missing in pre- and post-check!!!\n",aftersite[i]) 
				else if (stcmdBef==0) output=sprintf("%-10s: state printout missing in precheck!!!\n",aftersite[i])
				else if (stcmdAft==0) output=sprintf("%-10s: state printout missing in postcheck!!!\n",aftersite[i])
				print output >> disFile
				print output >> disFileLess
			}
			if (strcmdAft==1 && strcmdBef==1)
			{
				for (downa in downAfter)
					for (downb in downBefore)
						if (downAfter[downa]==downBefore[downb]) { delete downAfter[downa] ; delete downBefore[downb] }
				for (downa in downAfter)
				{
					if (downAfter[downa] != "")
					{
						printf("%-10s  %s\n",aftersite[i],downAfter[downa]) >> cellFile
						foundDown=1
					}
				}
				for (downb in downBefore)
				{
					if (downBefore[downb] != "")
					{
						printf("%-10s  %s\n",aftersite[i],downBefore[downb]) >> cellFileLess
						foundDownLess=1
					}
				}
				if (foundDown==1) print "" >> cellFile
				if (foundDownLess==1) print "" >> cellFileLess
			}
			else
			{
				if (strcmdAft==0 && strcmdBef==0)	output=sprintf("%-10s: str printout missing in pre- and post-check!!!\n",aftersite[i]) 
				else if (strcmdBef==0) output=sprintf("%-10s: str printout missing in precheck!!!\n",aftersite[i])
				else if (strcmdAft==0) output=sprintf("%-10s: str printout missing in postcheck!!!\n",aftersite[i])
				print output >> cellFile
				print output >> cellFileLess
			}
			printf("Done.\n")
		}
	}
	printf("Result files are saved in %s\n",resultdir)
}
'
}
	
function changepw()
{
$gawk -v resultdir="$resultdir" -v ipdatabase="$ipdatabase" -v sitefile="$sitefile" '
BEGIN {
	chpwDir=sprintf("%s/telbatch_cmdfiles",resultdir)
	system(sprintf("mkdir -p %s",chpwDir))
	while (getline < ipdatabase)
	{
		gsub("\r","")
		if (NF > 2)
		{
			site=$1
			ip[site]=$2
			pw[site]=$3
		}
	}
	close(ipdatabase)
	while (getline < sitefile)
	{
		gsub("\r","")
		site=$1
		if (ip[site] != "" && pw[site] != "")
		{
			print "passwd" >    sprintf("%s/%s.cmd",chpwDir,site)
			print "ericsson" >> sprintf("%s/%s.cmd",chpwDir,site)
			print pw[site]   >> sprintf("%s/%s.cmd",chpwDir,site)
			print pw[site]   >> sprintf("%s/%s.cmd",chpwDir,site)
		}
	}
	close(sitefile)
	printf("Command files are saved in %s\n",chpwDir)
}
'
}

diff=0
after=0
before=0
chpw=0
while getopts "a:b:p:" options
do
case $options in
a) afterdir=$OPTARG 
   if [[ ! -d $afterdir ]] ; then echo "Directory $afterdir not found. Exiting..." ; exit 1 ; fi
  ;;   
b) beforedir=$OPTARG
   if [[ ! -d $beforedir ]] ; then echo "Directory $beforedir not found. Exiting..." ; exit 1 ; fi
  ;;
p) ipdatabase=$OPTARG ;    chpw=1
   if [[ ! -f $ipdatabase ]] ; then echo "File $ipdatabase not found. Exiting..." ; exit 1 ; fi
   ;;
*) print_usage ; exit 1
  ;;
esac
done 
shift $(($OPTIND - 1))
#if test $OPTIND -eq 1 ; then print_usage ; exit 1; fi

if [[ -d $afterdir && -d $beforedir ]] ; then diff=1 ; fi

case $# in
2)  if test $diff -eq 0 ; then
	    if test -f "$2" ; then inputfile="$2" ; input="file" ; inputbase=$(basename $inputfile)
	    elif test -d "$2" ; then inputdir="$2" ; input="dir" ; inputbase=$(basename $inputdir)
	    else echo "File/Directory $2 not found. Exiting...." ; exit 1
	    fi
	    if test -f "$1" ; then reffile="$1" 
	    else echo "Reference file $1 not found. Exiting...." ; exit 1
	    fi
    fi	    
    ;;    
1) if test $chpw -eq 0 ; then print_usage ; exit 1 
   elif [[ -f $1 ]] ; then sitefile=$1
   else echo "Cannot find sitefile $1. Exiting..." ; exit 1
   fi
   ;;
*) if test $diff -eq 0 ; then print_usage ; exit 1 ; fi
  ;;   
esac

date_time=$(date +%y%m%d-%H%M)
if test $chpw -eq 1 ; then resultdir=${logdir}/${date_time}_chpw
elif test $diff -eq 1 ; then  resultdir=${logdir}/${date_time}_Diff
else resultdir=${logdir}/${date_time}_${inputbase}
fi
if ! mkdir -p $resultdir ; then "Failed to create result directory: $resultdir . Exiting ..." ; exit 1 ; fi 

if [[ $diff -eq 0 && $chpw -eq 0 ]] ; then netcheck 
elif [[ $diff -eq 1 ]] ; then diffcheck 
elif [[ $chpw -eq 1 ]] ; then changepw
fi

