#!/bin/ksh

Version="autonwkconfig.sh Version 19.67a"

setup_rtn()
{
	mkdir $INSTALLPATH/tools/NWKpolicies >/dev/null 2>&1
	rm -rf $INSTALLPATH/tools/NWKpolicies/*.* >/dev/null 2>&1
	clear
	echo -e "$GREEN_FG>>> $Version$DEF"
	echo -e "\n=============================================< $Version >=================================================="
	echo -e "This script creates .bat and .sh script files used to automatically configure the Networker resources required by ADMe."
	echo -e "Input data is taken from various ADMe configuration files, therefore if not fully configured resulting Networker policies will be incomplete."
	echo -e "\nThe resulting .bat files can be optionally transferred to the Networker server and executed there to establish the required resources."
	echo -e ""
	echo -e "\n==============================================================================================================================="
}

media_pool_rtn()
{
	while true
	do
	echo -e "\n$GREEN_FG A flag file is used to retain two related Media Pool names (per line) each assigned a unique retention value supporting the "
	echo -e " normal month to month retetion and a yearly retetion value. The file can be manually edited to add additional lines useful when multiple"
	echo -e " related Media Pool names are routinely needed.$DEF\n"

	if [ ! -s $HOMEPATH/.mediapools.cfg ];then echo "MediaPool=ADME1Years,1 years YearlyPool=ADME5Years,5 years" > $HOMEPATH/.mediapools.cfg; fi
	linecnt="$(wc -l $HOMEPATH/.mediapools.cfg | awk '{print $1}')"
	cat $HOMEPATH/.mediapools.cfg |sort -u > $HOMEPATH/.mediapools.tmp
	mv $HOMEPATH/.mediapools.tmp $HOMEPATH/.mediapools.cfg
	cat $HOMEPATH/.mediapools.cfg | grep -n . | sed -n "s/:/: /"gp
	echo -e "\n========================================================================================\n"

		echo -e "$CYAN_FG Choose by$WHITE_FG Row-#$CYAN_FG from above list the desired Media Pool set to use.$WHITE_FG E=Edit File$DEF > $Asciesc"; read mediax
		if [ "$mediax" = "E" -o "$mediax" = "e" ]
		then
			vi $HOMEPATH/.mediapools.cfg; mediax="1"
			continue
		fi
		if [ "$mediax" -lt "1" -o "$mediax" -gt "$linecnt" ];then continue; fi
		media1="$(sed -n "$mediax,$mediax"p $HOMEPATH/.mediapools.cfg | awk -F= '{print $2}' | awk -F, '{print $1}')"
		ret1="$(sed -n "$mediax,$mediax"p $HOMEPATH/.mediapools.cfg | awk -F= '{print $2}' | awk -F, '{print $2}' | awk '{print $1,$2}')"
		media2="$(sed -n "$mediax,$mediax"p $HOMEPATH/.mediapools.cfg | awk -F= '{print $3}' | awk -F, '{print $1}')"
		ret2="$(sed -n "$mediax,$mediax"p $HOMEPATH/.mediapools.cfg | awk -F= '{print $3}' | awk -F, '{print $2}' | awk '{print $1,$2}')"
# echo "DEBUG1 - media1=$media1 ret1=$ret1  media2=$media2 ret2=$ret2"
		MediaPool="$media1"; MRetValue="$ret1"	
		YearlyPool="$media2"; YRetValue="$ret2"	
		break	
	done	
	

	while true
	do
		mnew=0; ynew=0
		echo -e "\n$GREEN_FG Enter a Networker$WHITE_FG MEDIA-POOL-NAME$GREEN_FG to be used for$WHITE_FG Month-to-Month$GREEN_FG Tapeout migrations.\n\n [$WHITE_FG Q$CYAN_FG=Quit$WHITE_FG Enter$CYAN_FG=Your-Media-Pool-Name or$WHITE_FG Def=$MediaPool]$DEF > $Asciesc"; read media1
		if [ "$media1" = "" ];then MediaPool="$MediaPool"
		elif [ "$media1" = "q" -o  "$media1" = "Q" ];then exit
		else
			MediaPool="$media1"; mnew=1
		fi
		echo -e "\n$RED_BG$WHITE_FG NOTE: $DEF Valid entries must conform as shown: # weeks, # months, # years - 8 weeks or 1 years etc."
		echo -e "\n$GREEN_FG Enter desired$WHITE_FG RETENTION$GREEN_FG value to be used for$WHITE_FG Month-to-Month$GREEN_FG Tapeout migrations.\n\n [$WHITE_FG Q$CYAN_FG=Quit$WHITE_FG Enter$CYAN_FG=Your-Retntion-Value or$WHITE_FG Def=$MRetValue]$DEF > $Asciesc"; read ret1

		if [ "$ret1" = "" ];then MRetValue="$MRetValue"
		elif [ "$ret1" = "q" -o  "$ret1" = "Q" ];then exit
		elif [ "$ret1" != "" ]
		then
			if [ "$(echo "$ret1" | egrep -c "days|weeks|months|years")" -eq "0" ]
			then
				echo -e "\n$RED_BG$WHITE_FG ERROR: $DEF An invalid retention unit has been specified.... looping back!"
				continue
			else
				MRetValue="$ret1"; mnew=1
			fi
		fi

		echo -e "\n$GREEN_FG Enter a Networker$WHITE_FG MEDIA-POOL-NAME$GREEN_FG to be used for$WHITE_FG End-Of-Year$GREEN_FG Tapeout migrations.\n\n [$WHITE_FG Q$CYAN_FG=Quit$WHITE_FG N$RED_FG=NOT-APPLICABLE$WHITE_FG Enter$CYAN_FG=Your-Media-Pool-Name$CYAN_FG or$WHITE_FG Def=$YearlyPool]$DEF > $Asciesc"; read media2
# set -x
		if [ "$media2" = "" ];then YearlyPool="$YearlyPool"
		elif [ "$media2" = "q" -o  "$media2" = "Q" ];then exit
		elif [ "$media2" = "N" -o "$media2" = "n" ]
		then
			YearlyPool="NOT-APPLICABLE"; YRetValue="n/a"; ynew=1
		else
			YearlyPool="$media2"; ynew=1
		fi

		if [ "$YearlyPool" != "NOT-APPLICABLE" ]
		then
			echo -e "\n$RED_BG$WHITE_FG NOTE: $DEF Valid entries must conform as shown: # weeks, # months, # years - 1 months or 1 years etc."
			echo -e "\n$GREEN_FG Enter desired$WHITE_FG RETENTION$GREEN_FG value to be used for$WHITE_FG End-Of-Year$GREEN_FG Tapeout migrations.\n\n [$WHITE_FG Q$CYAN_FG=Quit$WHITE_FG Enter$CYAN_FG=Your-Retntion-Value or$WHITE_FG Def=$YRetValue]$DEF > $Asciesc"; read ret2
		fi

		if [ "$ret2" = "" ];then YRetValue="$YRetValue"
		elif [ "$ret2" = "q" -o  "$ret2" = "Q" ];then exit
		elif [ "$ret2" != "" ]
		then
			if [ "$(echo "$ret2" | egrep -c "days|weeks|months|years")" -eq "0" ]
			then
				echo -e "\n$RED_BG$WHITE_FG ERROR: $DEF An invalid retention unit has been specified.... looping back!"
				continue
			else
				YRetValue="$ret2"; ynew=1
			fi
		fi

		echo -e "\n$DEF======================< Media-Pool & Retention Summary >==============================="
		echo -e "\n$GREEN_FG Month-to-Month Pool Name:\t   $WHITE_FG $MediaPool$GREEN_FG\tRetention-Period:$WHITE_FG $MRetValue$DEF"
		if [ "$ynew" -ne "1" ]
		then
			echo -e "$GREEN_FG Yearly Pool Name:\t\t   $WHITE_FG $YearlyPool$GREEN_FG \tRetention-Period:$WHITE_FG $YRetValue$DEF"
		fi
		echo -e "\n$RED_BG$WHITE_FG WARNING: $DEF The above media pools must be manually predefined within Networker prior to establishng additional policies."
		echo -e "\n$DEF================================================================================================================="
		warning=0
		while true
		do
			if [ "$warning" -eq "0" ]
			then
				echo -e "\n$CYAN_FG Confirm above$WHITE_FG Media-Pool$CYAN_FG names and their their planned retention values are accurate and exist.$WHITE_FG Y=$CYAN_FG=Yes$WHITE_FG N$CYAN_FG=No$DEF > $Asciesc"; read confirm
			else
				echo -e "\n$RED_BG$WHITE_FG Must Confirm$DEF$CYAN_FG above$WHITE_FG Media-Pool$CYAN_FG names and their their planned retention values are accurate and exist.$WHITE_FG Y=$CYAN_FG=Yes$WHITE_FG N$CYAN_FG=No$DEF > $Asciesc"; read confirm
			fi
			if [ "$confirm" = "Y" -o "$confirm" = "y" ]
			then
				if [ "$mnew" -eq "1" -a "$ynew" -ne "1" ]
				then
					egrep -v "MediaPool=$MediaPool" $HOMEPATH/.mediapools.cfg > $HOMEPATH/.mediapools.tmp
					echo "MediaPool=$MediaPool,$MRetValue YearlyPool=n/a,n/a" >> $HOMEPATH/.mediapools.tmp
					mv $HOMEPATH/.mediapools.tmp $HOMEPATH/.mediapools.cfg
				elif [ "$mnew" -eq "1" -a "$ynew" -eq "0" ]
				then
					egrep -v "^MediaPool=$MediaPool" $HOMEPATH/.mediapools.cfg > $HOMEPATH/.mediapools.tmp
                                        echo "MediaPool=$MediaPool,$MRetValue YearlyPool=$YearlyPool,$YRetValue" >> $HOMEPATH/.mediapools.tmp
                                        mv $HOMEPATH/.mediapools.tmp $HOMEPATH/.mediapools.cfg
				fi
				return
			elif [ "$confirm" = "" ]
			then
				warning=1
				continue
			else break; fi
		done
	done
}

build_policy_rtn()
{
	echo -e "\n$CYAN_FG When$WHITE_FG Re-Establishing$CYAN_FG existing NWK policy definitions, delete the existing definitions?$WHITE_FG [Y or N Def=Y]$DEF :> $Asciesc";read redo
	if [ "$redo" = "" -o "$redo" = "Y" -o "$redo" = "y" ];then Redo="1"
	elif [ "$redo" = "N" -o "$redo" = "n" ];then Redo="0"
	else Redo="0"; fi

	while true
	do
		echo -e "\n$CYAN_FG Enter the $WHITE_FG NetWorker Policy Name$CYAN_FG to use.$WHITE_FG Def=ADME $DEF :> $Asciesc";read policyname
		if [ "$policyname" = ""  ];then break
		else
			NWKPOLICY="$policyname"; break
		fi
	done

	echo
	stagingservers="$(egrep "^UNIXSS|^WINDOWSS" $INSTALLPATH/etc/atoenv.cf* | grep -v "=n/a" | awk -F: '{print $2}' | sort -u | egrep -v "_a$|_b$|_c$|_d$|_e$|_f$|_g$|_h$|_i$|_j$|_k$|_l$" | grep -n "^" | sed -n "s/:/.\t/"gp )"
	stagecount="$(echo "$stagingservers" | wc -l | awk '{print $1}')"
	echo "$stagingservers"
set -
	echo -e "\n$RED_BG$WHITE_FG NOTE: $DEF When more than one staging server exists within your setup,"
	echo -e "        this process must be executed against each as required."
	echo -e "\n$DEF========================================================================================================="

	while true
	do
		echo -e "\n$CYAN_FG Enter a$WHITE_FG Staging Server$CYAN_FG name to configure by$WHITE_FG Row-#$CYAN_FG?$WHITE_FG [Def=$BUSERVER_NAME]$DEF: > $Asciesc";read stage
		if [ "$stage" -gt "0" -a "$stage" -le "$stagecount" ]
		then
			STGSERVER="$(echo "$stagingservers" | grep "^$stage" | head -1 | awk -F/ '{print $NF}')"; break
		elif [ "$stage" -eq "" ]
		then
			STGSERVER="$BUSERVER_NAME"; break
		fi
	done

	if [ "$BUSERVER_NAME" != "$STGSERVER" ]
	then
		warning=0
		while true
		do
			if [ "$warning" -eq "0" ]
			then
				echo -e "\n$CYAN_FG Is this staging server$WHITE_FG [$STGSERVER]$CYAN_FG a Networker Storage node?$WHITE_FG Y or N $DEF :> $Asciesc";read snode
			else
				echo -e "\n$RED_BG$WHITE_FG Must Confirm $DEF$CYAN_FG Is this staging server$WHITE_FG [$STGSERVER]$CYAN_FG a Networker Storage node?$WHITE_FG Y or N $DEF :> $Asciesc";read snode
			fi
			if [ "$snode" = "N" -o "$snode" = "n" ]
			then
				NWKSNODE="$BUSERVER_NAME"
				break
			elif [ "$snode" = "Y" -o "$snode" = "y" ]
			then
				NWKSNODE="$STGSERVER"; break
			fi
			warning=1
		done
	else
		NWKSNODE="$STGSERVER"
	fi
	
	rm -rf $WINNWK NWKclients.dat >/dev/null 2>&1
	echo "echo on" > $WINNWK
# ADAM OS issue
	GroupList="$(grep -v "^#" $CFG | awk -F, '{print $1"\tOS="$15}' | sort -u | grep .)"
	GroupList="$(grep -v "^#" $CFG | awk -F, '{print $1}' | sort -u | grep .)"
	echo "\nrem Establish Policy Name:" >> $WINNWK
	echo "$BACKUPPRODUCTHOMEWIN/nsrpolicy policy create -p $NWKPOLICY" >> $WINNWK
	echo "rem" >> $WINNWK

	echo
	echo "\n$GroupList" | grep . | grep -v "OS=$" | grep -n "^" | sed -n "s/:/:\t/"gp
	echo -e "\n$DEF========================================================================================================="
	while true
	do
		dolist=""
		echo -e "\n$CYAN_FG Enter by Row-Number(s) a space separated list of ADMe group names to be configured in Networker.$WHITE_FG Example: 1 3 5 etc. or A=ALL $DEF\n >>> $Asciesc"; read policies
		if [ "$policies" = "a" -o "$policies" = "A" ];then dolist="$GroupList"
		elif [ "$policies" = "" ];then continue
		elif [ "$policies" != "" ]
		then
			for p in $policies
			do
				grpx="$(echo "$GroupList" | sed -n "$p,$p"p)"
				dolist="$dolist $grpx"
			done
		fi
		break
	done

	for x in $dolist
        do
		if [ "$(echo "$x" | egrep -c "^OS=")" -gt "0" ];then continue; fi

                echo " Created Networker syntax for ADMe Group=$x"
		rm -rf $HOMEPATH/$x.bat $HOMEPATH/$x.sh >/dev/null 2>&1
		serverpolicy="$(grep "^$x" $CFG | head -1 | awk -F, '{print $14}' | awk '{print $NF}')"
		endofyearpolicy="$(grep "^$x" $CFG | head -1 | awk -F, '{print $13}' | awk '{print $NF}')"
		if [ "$serverpolicy" = "n/a" ];then serverpolicy="$x";fi
		if [ "$endofyearpolicy" = "n/a" ];then endofyearpolicy="Y$x";fi

# ============> Delete or establish new NWK group name
		if [ "$Redo" = "1" ]
		then
			echo "\nrem This code will delete required components if they exist prior to recreating for ADMe group name $x" >> $HOMEPATH/$x.bat
			if [ "$YearlyPool" != "NOT-APPLICABLE" ]
			then
				echo "\nrem This code will delete required components for Yearly tapeouts if they exist prior to recreating them for ADMe group name $x" >> $HOMEPATH/$x.bat
				echo "$BACKUPPRODUCTHOMEWIN/nsrpolicy action delete -p $NWKPOLICY -w $endofyearpolicy -A backup 2>nul" | sed -n "s/\//\\\/"gp >> $HOMEPATH/$x.bat
				echo "$BACKUPPRODUCTHOMEWIN/nsrpolicy workflow delete -p ADME -w Y$x 2>nul" | sed -n "s/\//\\\/"gp >> $HOMEPATH/$x.bat
				echo "$BACKUPPRODUCTHOMEWIN/nsrpolicy group delete -g Y$x 2>nul" | sed -n "s/\//\\\/"gp >> $HOMEPATH/$x.bat
			fi
			echo "\nrem This code will delete required components for Monthly tapeouts if they exist prior to recreating them for ADMe group name $x" >> $HOMEPATH/$x.bat
			echo "$BACKUPPRODUCTHOMEWIN/nsrpolicy action delete -p $NWKPOLICY -w $serverpolicy -A backup 2>nul" | sed -n "s/\//\\\/"gp >> $HOMEPATH/$x.bat
			echo "$BACKUPPRODUCTHOMEWIN/nsrpolicy workflow delete -p ADME -w $x 2>nul" | sed -n "s/\//\\\/"gp >> $HOMEPATH/$x.bat
			echo "$BACKUPPRODUCTHOMEWIN/nsrpolicy group delete -g $x 2>nul" | sed -n "s/\//\\\/"gp >> $HOMEPATH/$x.bat
		fi
		echo "\nrem This code will create required components for Monthly tapeouts for ADMe group name $x:" >> $HOMEPATH/$x.bat
		echo "$BACKUPPRODUCTHOMEWIN/nsrpolicy group create client -g $x" | sed -n "s/\//\\\/"gp >> $HOMEPATH/$x.bat
		echo "$BACKUPPRODUCTHOMEWIN/nsrpolicy workflow create -p $NWKPOLICY -w $x -g $x -u no -E yes" | sed -n "s/\//\\\/"gp >> $HOMEPATH/$x.bat
		echo "$BACKUPPRODUCTHOMEWIN/nsrpolicy action create backup traditional -p $NWKPOLICY  -w $serverpolicy -A backup -e yes -o $MediaPool -g $NWKSNODE -t full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full -P month -r \"$MRetValue\" -F \"abort workflow\"  -R 0 -I 0" | sed -n "s/\//\\\/"gp >> $HOMEPATH/$x.bat
		if [ "$YearlyPool" != "NOT-APPLICABLE" ]
		then
			echo "\nrem This code will create required components for Yearly tapeouts for ADMe group name $x:" >> $HOMEPATH/$x.bat
			echo "$BACKUPPRODUCTHOMEWIN/nsrpolicy group create client -g Y$x" | sed -n "s/\//\\\/"gp >> $HOMEPATH/$x.bat
			echo "$BACKUPPRODUCTHOMEWIN/nsrpolicy workflow create -p $NWKPOLICY -w Y$x -g Y$x -u no -E yes" | sed -n "s/\//\\\/"gp >> $HOMEPATH/$x.bat
			echo "$BACKUPPRODUCTHOMEWIN/nsrpolicy action create backup traditional -p $NWKPOLICY -w $endofyearpolicy -A backup -e yes -o $YearlyPool -g $NWKSNODE -t full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full,full -P month -r \"$YRetValue\" -F \"abort workflow\"  -R 0 -I 0" | sed -n "s/\//\\\/"gp >> $HOMEPATH/$x.bat
		fi
		if [ "$(echo "$x" | grep -c "^Y" )" -eq "0" ]
		then
			if [ -s $INSTALLPATH/etc/admbatch-$x.cfg ]
			then
				if [ "$(grep -c "\-inc" $INSTALLPATH/etc/admbatch-$x.cfg)" -eq "1" ];then KeyWord="INCREMENTAL"; else KeyWord="BYDATE";fi 
			elif [ "$(echo "$x" | egrep -c "^OS=")" -gt "0" ];then continue
			else
				echo "\n$RED_BG$WHITE_FG WARNING: $DEF Job policy name$RED_FG [$x]$DEF not defined, will assume it is non-incremental using keyword BYDATE\n"
				KeyWord="BYDATE"
			fi
			stagingpath="$(grep "^$x" $CFG | head -1 | awk -F, '{print $10}')"
			ostype="$(grep "^$x" $CFG | head -1 | awk -F, '{print $15}')"
			if [ "$ostype" = "WINDOWS" ]
			then
# ============================> Windows paths need to be escape due to the colon after drive letter and the multiple back slashes
				if [ "$(echo "$stagingpath" | grep -c "/vmimg")" -ne "0" ];then vmimg="1"; else vmimg="0"; fi
# echo "DEBUG - vmimg=$vmimg Stagingpath=$stagingpath"
				stagingpath_="$(echo "$stagingpath" | sed -n "s/\//\\\\\\\\\\\/"gp)"
				if [ "$vmimg" -eq "1" ]
				then
					echo "delete name:$STGSERVER;type:NSR client;aliases:$STGSERVER;comment:ADME-Job $x;Save operations:\"PSS:timeout_mins=0;vss:*=off\";Parallel save streams per save set: Enabled;parallelism: 24;protection group list: Y$x, $x;save set:\"$stagingpath_\\\\\BYDATE\";" | sed -n "s/\\v/\\\v/"gp >> $HOMEPATH/NWKclients.dat
					echo "\n" >>  $HOMEPATH/NWKclients.dat
					echo "create name:$STGSERVER;type:NSR client;aliases:$STGSERVER;comment:ADME-Job $x;Save operations:\"PSS:timeout_mins=0;vss:*=off\";Parallel save streams per save set: Enabled;parallelism: 24;protection group list: Y$x, $x;save set:\"$stagingpath_\\\\\BYDATE\";" | sed -n "s/\\v/\\\v/"gp >> $HOMEPATH/NWKclients.dat
					echo "\n" >>  $HOMEPATH/NWKclients.dat
				else
					echo "delete name:$STGSERVER;type:NSR client;aliases:$STGSERVER;comment:ADME-Job $x;Save operations:\"PSS:timeout_mins=0;vss:*=off\";Parallel save streams per save set: Enabled;parallelism: 24;protection group list: Y$x, $x;save set:\"$stagingpath_\\\\\\$KeyWord\";"  >> $HOMEPATH/NWKclients.dat
					echo "\n" >>  $HOMEPATH/NWKclients.dat
					echo "create name:$STGSERVER;type:NSR client;aliases:$STGSERVER;comment:ADME-Job $x;Save operations:\"PSS:timeout_mins=0;vss:*=off\";Parallel save streams per save set: Enabled;parallelism: 24;protection group list: Y$x, $x;save set:\"$stagingpath_\\\\\\$KeyWord\";" >> $HOMEPATH/NWKclients.dat
					echo "\n" >>  $HOMEPATH/NWKclients.dat
				fi
			else
				stagingpath_="$stagingpath"
				echo -e "delete name:$STGSERVER;type:NSR client;aliases:$STGSERVER;comment:ADME-Job $x;Save operations:\"PSS:timeout_mins=0\";Parallel save streams per save set: Enabled;parallelism: 24;protection group list: Y$x, $x;save set:\"$stagingpath_/$KeyWord\";\n" >> $HOMEPATH/NWKclients.dat
				echo -e "create name:$STGSERVER;type:NSR client;aliases:$STGSERVER;comment:ADME-Job $x;Save operations:\"PSS:timeout_mins=0\";Parallel save streams per save set: Enabled;parallelism: 24;protection group list: Y$x, $x;save set:\"$stagingpath_/$KeyWord\";\n" >> $HOMEPATH/NWKclients.dat
			fi
		fi
		cat $HOMEPATH/$x.bat >> $WINNWK
        done
	mv $HOMEPATH/*.bat $WINNWK $HOMEPATH/NWKclients.dat $HOMEPATH/NWKpolicies >/dev/null 2>&1
}

transfer_rtn()
{
	warning=0
	while true
	do
		noenv=0
		if [ "$warning" -eq "0" ]
		then
			echo -e "\n$WHITE_FG>>> TRANSFER$CYAN_FG generated files to the$WHITE_FG NetWworker Server$CYAN_FG?$WHITE_FG Y or N $DEF :> $Asciesc";read transfer
		else
			echo -e "\n$RED_BG$WHITE_FG Must COnfirm $DEF$WHITE_FG>>> TRANSFER$CYAN_FG generated files to the$WHITE_FG NetWworker Server$CYAN_FG?$WHITE_FG Y or N $DEF :> $Asciesc";read transfer
		fi
	
		if [ "$transfer" = "" ]
		then
			warning=1; continue
		elif [ "$transfer" = "N" -o "$transfer" = "n" ];then break; fi

			transferservers="$(grep "$BUSERVER_NAME" $INSTALLPATH/tmp/atocfg/.input.dat1.discover | sort -k1 | grep -n "^" | sed -n "s/:/: /"gp)"
			if [ "$transferservers" = "" ]
			then 
				echo -e "\n$RED_FG The NetWorker server name is not present in an ADMe Environment file, and it does not appear to be activated to Avamar ... Exiting $DEF"; exit 1
			else
				echo -e "\n$CYAN_FG The NetWorker server is activated to Avamar with the following threads:$DEF"
				noenv=1
			fi

		transxcnt="$(echo "$transferservers" | wc -l | awk '{print $1}')"
		echo -e "\n$transferservers" 
		envstatus_rtn
		
		echo -e "\n$CYAN_FG Pick an idle$WHITE_FG MCS Recovery Thread$CYAN_FG by$WHITE_FG Row-#$CYAN_FG to use for the transfer?$WHITE_FG [Def=1]$DEF :> $Asciesc";read transx
		if [ "$transx" = "" ];then transx="1";fi
		if [ "$transx" -gt "0" -a "$transx" -le "$transxcnt" ]
		then
			if [ "$noenv" = "1" ]
			then	
				transxclient="$(echo "$transferservers" | grep "^$transx" | head -1 |  awk '{print $2}' | sort -u)"
				transx="$transxclient"
			else
				transx="$(echo "$transferservers" | grep "^$transx" | head -1 | awk -F/ '{print $NF}' |sort -u)"
			fi
		fi

		if [ "$transfer" = "Y" -o "$transfer" = "y" ]
		then	
			echo -e "\nTransferring files Please wait ....\n"
			/usr/local/avamar/bin/avtar -c --nocache --acnt=/ADME/admepseudo20 --label=NWKpolicies --expires=1 --quiet $HOMEPATH/NWKpolicies >/dev/null
			labelnumx="$(/usr/local/avamar/bin/avtar --backups --acnt=/ADME/admepseudo20 --quiet | grep "NWKpolicies" | head -1 | awk '{print $3}')"
			activityid="$(mccli backup restore --domain=/ADME --name=admepseudo20 --dest-client-name=/ADME/$transx --dest-dir=C:/ADME-NWKpolicies --cmd=--overwrite=newest --plugin=3001 --labelNum=$labelnumx --cmd=--preservepaths=false --data=$HOMEPATH/NWKpolicies | grep "activity-id" | awk '{print $2}')"
set -
			while true
			do
				mccli activity show | grep $activityid 
				if [ "$(mccli activity show | grep $transx | grep "Restore" | head -1 | grep -c "Completed")" -gt "0" ]
				then
					echo "\nTransfer Completed...\r"
					break
				else
					echo "Transfer in Progress...\c"
					sleep 2; continue
				fi
				
			done

			echo -e "\n$RED_BG$WHITE_FG NOTE:$DEF$CYAN_FG The generated .bat & .dat files have been transferred to$WHITE_FG C:\\ADME-NWKpolicies$CYAN_FG on the Networker server [$WHITE_FG$BUSERVER_NAME$CYAN_FG]\n       from where they must be executed from a CMD prompt"
			echo "\n           1. The generated .bat & .dat files are used to establish workflows, actions, groups and client resources as required."
			echo "           2. Each$WHITE_FG <group-name>.bat$CYAN_FG file(s) can be run individually or$WHITE_FG NWKpolicies.bat$CYAN_FG can be run containing all chosen group names."
			echo "           3. Use the following call to establish staging client resource definitions after the .bat files have been run."
			echo "\n                     $GREEN_FG C:\ADME-NWKpolicies$WHITE_FG nsradmin -i NWKclients.dat$DEF\n\n"
			break
		else continue; fi
	done
}

cleanup_rtn()
{
	rm -rf alldata.tmp $groupfile $allclients $joblist cli*.srt* grplist.dat admeconfigured.txt .flatbuid.tmp cligroup_* $alldata$orig  >/dev/null 2>&1 
}

envstatus_rtn()
{
	idlecnt="0"; activecnt="0"
        echo "\n$CYAN_FG Current Environment File Status\n$DEF"
        for x in $(awk -F, '{print $1}' $INSTALLPATH/jobstats/environment.csv)
        do
        	if [ "$x" -eq "0" ];then continue; fi
                sserver_linux="$(cat $INSTALLPATH/jobstats/environment.csv | grep "^$x" | awk -F, '{print $11}' | head -1)"
                sserver_win="$(cat $INSTALLPATH/jobstats/environment.csv | grep "^$x" | awk -F, '{print $14}' | head -1)"
                if [ "$sserver_linux" != "n/a" ];then sserverx="$sserver_linux"; else sserverx="$sserver_win"; fi

                linex="$(expr $x + 1)"
                status="$(sed -n "$linex,$linex"p $INSTALLPATH/jobstats/environment.csv | awk -F, '{print $NF}')"

                if [ "$status" = "ACTIVE" ]
                then
               		echo "Env-$x:\t$GREEN_FG $status$DEF\t $sserverx"; activecnt="$(expr $activecnt + 1)"
                elif [ "$x" -eq "20" ]
                then
                        echo "Env-$x:\t$RED_FG RESERVED$DEF"
                else
                        echo "Env-$x:\t $status\t $sserverx"; idlecnt="$(expr $idlecnt + 1)"
                fi
        done
        echo "\n$CYAN_FG Active-Count:$WHITE_FG $activecnt$CYAN_FG Idle-Count:$WHITE_FG $idlecnt$DEF\n\n"
}

# MAIN Main main
if [ -s /home/admin/admeadmin/tools/autonwkconfig.sh ]
then
 	INSTALLPATH="/home/admin/admeadmin"
elif [ -s /atoadmin/tools/autonwkconfig.sh ]
then
 	INSTALLPATH="/atoadmin"
else
 	INSTALLPATH="/home/admin/admeadmin"
fi
HOMEPATH="$INSTALLPATH/tools"
echo "DEBUG - $HOMEPATH"
Korn="$(rpm -qa | grep ksh | head -1 | awk '{print $1}')"
if [ "$(echo "$Korn" | grep -c "50")" -ne "0" ];then Asciesc="\c"; else Asciesc="\c\r"; fi

RED_FG="\033[31;1m"; GREEN_FG="\033[32;1m"; BLUE_FG="\033[34;1m"; MAG_FG="\033[35;1m"; CYAN_FG="\033[36;1m"; WHITE_FG="\033[37;1m"; GRAY_FG="\033[30;1m"
RED_BG="\033[41;1m"; GREEN_BG="\033[42;1m"; BLUE_BG="\033[44;1m"; MAG_BG="\033[45;1m"; CYAN_BG="\033[46;1m"; WHITE_BG="\033[47;1m"; YELLOW_FG="\033[1;33m"
DEF="\033[0m"; BOLD="\033[1m"; BLINK="\033[5m"; NOBLINK="\033[25m"; USCORE="\033[4m"; YELLOW_BG="\033[1;43m" 
CFG="$INSTALLPATH/etc/admeclient.cfg"; GroupList=""; NWKPOLICY="ADME"
BACKUPPRODUCTHOMEWIN="$(grep "^BACKUPPRODUCTHOMEWIN=" $INSTALLPATH/etc/atoenv.cfg| head -1 | awk -F= '{print $2}')"
BACKUPPRODUCTHOMEUNIX="$(grep "^BACKUPPRODUCTHOMEUNIX=" $INSTALLPATH/etc/atoenv.cfg| head -1 | awk -F= '{print $2}')"
BUSERVER_NAME="$(grep "^BUSERVER_NAME=" $INSTALLPATH/etc/atoenv.cfg| head -1 | awk -F= '{print $2}')"; ThreadX="_c"
WINNWK="$HOMEPATH/NWKpolicies.bat"; LNXNWK="$HOMEPATH/NWKpolicies.sh"


setup_rtn
media_pool_rtn
build_policy_rtn
transfer_rtn
