#!/bin/ksh
# Written by: Adam Kirkpatrick 2019-01-13

Version="19.72a 2023-05-03"

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"; DASH="-"; INCLUDEEXPIRED_="N"
HOMEPATH="/home/admin/admeadmin"
CFG="$HOMEPATH/etc/atoclient.cfg"
CFG="$HOMEPATH/etc/admeclient.cfg"
Korn="$(rpm -qa | grep ksh | head -1 | awk '{print $1}')"
if [ "$(echo "$Korn" | grep -c "50")" -ne "0" ]
then
	Asciesc="\c"; Asciesc2="\r\c"
else
	Asciesc="\c\r"; Asciesc2="\r\c"
fi
# Asciesc="\c\r"

clear
echo -e "$GREEN_FG>>> Version: $Version\n"
echo "\n$RED_BG$WHITE_FG WARNING:$DEF$WHITE_FG THIS SCRIPT MUST ONLY BE RUN ON A TARGET AVAMAR OR AER BEING USED TO RECEIVE AER IMPORT DATA FROM TAPE$DEF"
echo "\n It will define adme job templates on a per client basis one for each available exported backup. The job templates will be saved to"
echo " file named <client-name.dat> where each line represents a job definition used to create a ADMe job policy. It will act on a single"
echo " client and backup based on its corresponding metadata attributes including original BU date, label-number, expiry date, plugin-ID"
echo " and expiry date captured from the AER metadata."
# echo "\n<<< Press Enter to Continue.. >>> $Asciesc"; read
nextnum="1"
ls -rtl $HOMEPATH/customize | grep "final.csv$" | awk '{print $NF}' | grep -n . | sed -n "s/:/. /"p > $HOMEPATH/tools/aermetadatafiles.tmp
echo "$GREEN_FG"
cat $HOMEPATH/tools/aermetadatafiles.tmp

if [ "$1" = "" ]
then
# 	echo "\n$CYAN_FG Enter by Row# or path & file name of an AER metadata csv file: >$DEF \c\r"; read inputfile
	echo "\n$CYAN_FG Enter by Row# or path & file name of an AER metadata csv file: >$DEF $Asciesc"; read inputfile
	if [ "$(echo "$inputfile" | grep -c "/")" -gt "0" ]
	then
		echo "\nUsing file name [$inputfile]..."
	elif [ "$inputfile" -gt "0" -a "$inputfile" -lt "20" ]
	then
		chosenfile="$(sed -n "$inputfile,$inputfile"p aermetadatafiles.tmp | awk '{print $NF}')"
		inputfile="$HOMEPATH/customize/$chosenfile"
	else continue; fi
else inputfile="$1"; fi
rm $HOMEPATH/tools/aermetadatafiles.tmp >/dev/null 2>&1

USECASE="$(grep "^BACKUPPRODUCT=" $HOMEPATH/etc/atoenv.cfg | awk -F= '{print $2}')"
while true
do
if [ -s "$inputfile" ]
then
# ====> Generate client name list
	echo
	awk -F\; '{print $5}' $inputfile | awk -F/ '{print $NF}' | sort -u -f | grep "."  > $HOMEPATH/tools/allclientlist.txt
# ====> Display numbered unique client name list
	grep -n "^" $HOMEPATH/tools/allclientlist.txt | sed -n "s/:/: /"p
# ====> Choose desired client name by row number
	echo "\n======================================================="
	maxline="$(wc -l $HOMEPATH/tools/allclientlist.txt | awk '{print $1}')"
	maxline="$(expr $maxline + 1)"
while true
do
	echo "\n$GREEN_FG Using input filename $inputfile]$DEF"
	echo "\n$CYAN_FG Choose by row number the client name:$WHITE_FG Q=Quit Def=$nextnum >$DEF $Asciesc"; read input
	if [ "$input" = "Q" -o "$input" = "q" ]
	then
		exit
	elif [ "$input" -eq "" ]
	then
		input="$nextnum"; nextnum="$(expr $nextnum + 1)"
		if [ "$nextnum" -gt "$maxline" ];then exit; fi
	elif [ "$input" -gt "0" ]
        then
		nextnum="$input"; nextnum="$(expr $nextnum + 1)"
		if [ "$nextnum" -gt "$maxline" ];then exit; fi
	fi
	if [ "$input" -lt "1" -o "$input" -gt "$maxline" ];then continue; else break; fi
done


# ====> Get the chosen client by name
	clientx="$(sed -n "$input,$input"p allclientlist.txt | awk '{print $1}' | head -1)"
# echo "DEBUG-1 clientx=$clientx"

# ====> Build default env file details in .aerjobsenv.dat
	if [ ! -s $HOMEPATH/tools/.aerjobsenv.dat ]
	then
		echo "1,E,C:/progra~1/avs/var" > $HOMEPATH/tools/.aerjobsenv.dat
		echo "2,F,C:/progra~1/avs/var2" >> $HOMEPATH/tools/.aerjobsenv.dat
		echo "3,G,C:/progra~1/avs/var3" >> $HOMEPATH/tools/.aerjobsenv.dat
		echo "4,H,C:/progra~1/avs/var4" >> $HOMEPATH/tools/.aerjobsenv.dat
		echo "5,I,C:/progra~1/avs/var5" >> $HOMEPATH/tools/.aerjobsenv.dat
		echo "6,J,C:/progra~1/avs/var6" >> $HOMEPATH/tools/.aerjobsenv.dat
		echo "7,K,C:/progra~1/avs/var7" >> $HOMEPATH/tools/.aerjobsenv.dat
		echo "8,L,C:/progra~1/avs/var8" >> $HOMEPATH/tools/.aerjobsenv.dat
	fi
# ====> Get the chosen Environment number to use

	lastenv="$(wc -l $HOMEPATH/tools/.aerjobsenv.dat | awk '{print $1}')"
	echo "$GREEN_FG\nRow-#\tEnv-#,Drive-Letter,Cache-Folder\n$DEF"
	cat $HOMEPATH/tools/.aerjobsenv.dat | grep -n . | sed -n "s/:/:  /"p
	echo "\n$RED_BG$WHITE_FG NOTE: $DEF If the above generic list does not match your setup, edit file $HOMEPATH/tools/.aerjobsenv.dat\n"
	while true
	do
		echo "\n$CYAN_FG Enter an ADMe Env-# to use by Row-# from above list: $WHITE_FG[Def=1]$CYAN_FG: >$DEF $Asciesc"; read envnum
		if [ "$envnum" -eq "1" -o "$envnum" -eq "" -o "$envnum" -le "$lastenv" ]
		then
			if [ "$envnum" -eq "" ];then envnum="1"; fi
			cachex="$(sed -n "$envnum,$envnum"p $HOMEPATH/tools/.aerjobsenv.dat | awk -F, '{print $3}')"
			FORMAT="$(sed -n "$envnum,$envnum"p $HOMEPATH/tools/.aerjobsenv.dat | awk -F, '{print $2}')"
			echo "\n$GREEN_FG Using: Env#:$WHITE_FG $envnum$GREEN_FG Cache-Folder:$WHITE_FG $cachex$GREEN_FG Format-Drv:$WHITE_FG $FORMAT$DEF"
			break
		else
			echo "\n$RED_FG Env-# chosen is out of range, Max allowed is $lastenv ...$DEF"
			continue
		fi
	done

	while true
	do
		if [ "$USECASE" != "avamar" ];then break; fi
		echo "\n$CYAN_FG Enter target Data-Domain-Index# to use: $WHITE_FG[Def=1]$CYAN_FG: >$DEF $Asciesc"; read ddrindex
		if [ "$ddrindex" -eq "" -o "$ddrindex" -eq "1" ]
		then
			DDR="~~ddr-index=1"; break
		elif [ "$ddrindex" -gt "1" -a "$ddrindex" -lt "10" ]
		then
			DDR="~~ddr-index=$ddrindex"; break
		else
			echo "\n$RED_FG DDR-Index-# chosen is out of range, Max allowed is 9 ...$DEF"
			continue
		fi
	done
	while true
	do
# 		if [ "$USECASE" != "avamar" ];then break; fi
		echo "\n$CYAN_FG Should ADMe automatically$WHITE_FG PURGE$CYAN_FG a successully migrated label number from the GSAN?: $WHITE_FG[Def=Y]$CYAN_FG: >$DEF $Asciesc"; read purgeit
		if [ "$purgeit" = "" -o "$purgeit" = "Y" -o "$purgeit" = "y" ]
		then
			PURGEIT="-purge"; break
		else
			PURGEIT=""; break
		fi
	done
	while true
	do
		echo "\n$CYAN_FG Include$WHITE_FG EXPIRED-BACKUPS$CYAN_FG within the Tracker csv file?$WHITE_FG [Current-Def=$INCLUDEEXPIRED_ Y=Yes N=No]$CYAN_FG: >$DEF $Asciesc"; read includeexpire
		if [ "$includeexpire" = "" -o "$includeexpire" = "N" -o "$includeexpire" = "n" ]
		then
			INCLUDEEXPIRED="N"; break
		elif [ "$includeexpire" = "Y" -o "$includeexpire" = "y" ]
		then
			INCLUDEEXPIRED_="Y"
			INCLUDEEXPIRED="Y"; break
		fi
	done
	while true
	do
		if [ "$USECASE" != "avamar" ]
		then
			TAGX="";break
		fi

		echo "\n$CYAN_FG Do you want to$WHITE_FG TAG$CYAN_FG the target destination client name? [$WHITE_FG Def=Y Example=AER]$CYAN_FG: >$DEF $Asciesc"; read tagx
		if [ "$tagx" = "" ]
		then
			TAGX="-AER"; break
		elif [ "$tagx" != "" ]
		then
			TAGX="-$tagx"; break
		fi
	done

# ====> create a csv for all entries pertaining to chosen client name
	grep -w "$clientx" $inputfile > $HOMEPATH/tools/clientx.csv
	lastline="$(wc -l clientx.csv | awk '{print $1}')"
	curline=0	
	rm $HOMEPATH/tools/$clientx.dat $HOMEPATH/tools/$clientx.tmp >/dev/null 2>&1
	echo
	while true
	do
		echo "Processing client [$clientx] line entry [$curline] ...$Asciesc2"
		if [ "$curline" -ge "$lastline" ];then break; fi
		if [ "$curline" -lt "$lastline" ];then curline="$(expr $curline + 1)"; fi
		linex="$(sed -n "$curline,$curline"p clientx.csv)"
# echo "DEBUG - $linex"
# read

		sizebytes="$(echo "$linex" | awk -F, '{print $11}')"
		origdate="$(echo "$linex" | awk -F\; '{print $2}' | awk -F\: '{print $2}' | sed -n "s/000$//"gp)"
		origdatehuman="$(date -d @$origdate '+%Y-%m-%d-%H-%M' 2>/dev/null)"
set -

		origlabelnum="$(echo "$linex" | awk -F\; '{print $6}' | awk -F\: '{print $2}')"
# ============> If the line entry has no labelnum field it cannot be processed, jam it to 0
		if [ "origlabelnum" -eq "" ];then origlabelnum="0"; fi
		echo "$origlabelnum" >> $HOMEPATH/tools/$clientx.tmp
		LABELNUM="$(grep -c "$origlabelnum$" $HOMEPATH/tools/$clientx.tmp)"
		if [ "$LABELNUM" -gt "1" -a "$origlabelnum" -ne "" ];then LABELNUM="DUPLABEL=$origlabelnum"; else LABELNUM="LABEL=$origlabelnum"; fi
# ============> Determined plugin type to insert proper select statement, support exists for vmimage, sql and FS
		plugin="$(echo "$linex" | awk -F\; '{print $7}' | awk -F\: '{print $2}')"
		if [ "$plugin" -eq "1016" -o "$plugin" -eq "3016" ];then pluginx="-vmimage"
		elif [ "$plugin" -eq "3006" ];then pluginx="-sql"
		elif [ "$plugin" -eq "3018" ];then pluginx="-exchvss"
		elif [ "$plugin" -eq "3015" ];then pluginx="-vss"
		elif [ "$plugin" -eq "8003" -o "$plugin" -eq "14003" ];then pluginx="-ndmp"
		elif [ "$plugin" -eq "3002" -o "$plugin" -eq "1002" -o "$plugin" -eq "2002" ];then pluginx="-ndmp"
		elif [ "$plugin" -eq "3026" ];then pluginx="-shptvss"
		elif [ "$plugin" -eq "3032" ];then pluginx="-hypervss"
		else pluginx=""; fi
		NWKSaveSetID="$(echo "$linex" | awk -F, '{print $2}')"
		Barcode="$(echo "$linex" | awk -F, '{print $14}')"
		ExportDate="$(echo "$linex" | awk -F, '{print $6}')"
		Savetime="$(echo "$linex" | awk -F, '{print $5}')"
		
		fullclientx="$(echo "$linex" | grep "$clientx" | awk -F\; '{print $5}' | awk -F/ '{print $NF}')"
		if [ "$fullclientx" != "$clientx" ]
		then
# 			echo "DEBUG2 - fullclientx=$fullclientx clientx=$clientx"
			continue
		fi
		expiredate="$(echo "$linex" | awk -F, '{print $10}')"
		A="$(date '+%Y%m%d')"
		B="$(date -d $expiredate +'%Y%m%d' 2>/dev/null)"

		expiredays="$(( (`date -d $B +%s 2>/dev/null` - `date -d $A +%s 2>/dev/null`) / 86400 ))"

		if [ "$expiredays" -lt "0" ];then EXPIRED="EXPIRED"; else EXPIRED=""; fi

		StageingPath="$(egrep "AER2DD0$envnum," $CFG | head -1 | awk -F, '{print $10}')"
		StageingOS="$(egrep "AER2DD0$envnum," $CFG | head -1 | awk -F, '{print $15}')"
		if [ "$USECASE" = "avamar" ]
		then
			if [ "$StageingOS" = "WINDOWS" ]
			then
				echo "adme -jobcreate 'j=AER2DD0$envnum,e=$envnum,g=AER2DD0$envnum,s=$pluginx -last_F -nday +30,m=-tpolicy \"~~expires=$expiredays $DDR ~~vardir=$cachex\" -aer $origdatehuman$DASH$origlabelnum -avamigrate /ADME/$clientx$TAGX $PURGEIT -upst FORMAT-$FORMAT -avtar,u=update' Barcode=$Barcode ExpireDays=$expiredays $EXPIRED $LABELNUM" >> $HOMEPATH/tools/$clientx.dat
			else
				echo "adme -jobcreate 'j=AER2DD0$envnum,e=$envnum,g=AER2DD0$envnum,s=$pluginx -last_F -nday +30,m=-tpolicy \"~~expires=$expiredays $DDR ~~vardir=$cachex\" -aer $origdatehuman$DASH$origlabelnum -avamigrate /ADME/$clientx$TAGX $PURGEIT -avtar,u=update' Barcode=$Barcode ExpireDays=$expiredays $EXPIRED $LABELNUM" >> $HOMEPATH/tools/$clientx.dat
			fi
		else
			if [ "$StageingOS" = "WINDOWS" ]
			then
				echo "adme -jobcreate 'j=AER2TAPE0$envnum,e=$envnum,g=AER2TAPE0$envnum,s=$pluginx -last_F,m=-aer $origdatehuman$DASH$origlabelnum -avamigrate /TAPE/$clientx $PURGEIT -upst FORMAT-$FORMAT -avtar,u=update' Barcode=$Barcode ExpireDays=$expiredays $EXPIRED $LABELNUM" >> $HOMEPATH/tools/$clientx.dat
			else
				echo "adme -jobcreate 'j=AER2TAPE0$envnum,e=$envnum,g=AER2TAPE0$envnum,s=$pluginx -last_F,m=-aer $origdatehuman$DASH$origlabelnum -avamigrate /TAPE/$clientx $PURGEIT -avtar,u=update' Barcode=$Barcode ExpireDays=$expiredays $EXPIRED $LABELNUM" >> $HOMEPATH/tools/$clientx.dat
			fi
		fi

# ============> Build tracker csv file
		trackerfilex="$(echo "$inputfile" | awk -F/ '{print $NF}' | sed -n "s/final.csv/tracker.csv/"gp)"

		if [ "$INCLUDEEXPIRED_" = "Y" -a "$expiredays" -lt "0" ]
		then
#			echo "$fullclientx,$plugin,$origdatehuman$DASH$origlabelnum,$origlabelnum,$Barcode,$envnum,$NWKSaveSetID,$ExportDate,$expiredays,$EXPIRED,$sizebytes,$StageingPath" >> $HOMEPATH/tools/$trackerfilex
			echo "$fullclientx,$plugin,$origdatehuman$DASH$origlabelnum,$origlabelnum,$Savetime,$Barcode,$envnum,$NWKSaveSetID,$ExportDate,$expiredays,$EXPIRED,$sizebytes,$StageingPath" >> $HOMEPATH/tools/$trackerfilex
		fi
		if [ "$expiredays" -gt "30" ]
		then
#			echo "$fullclientx,$plugin,$origdatehuman$DASH$origlabelnum,$origlabelnum,$Barcode,$envnum,$NWKSaveSetID,$ExportDate,$expiredays,NOT-EXPIRED,$sizebytes,$StageingPath" >> $HOMEPATH/tools/$trackerfilex
			echo "$fullclientx,$plugin,$origdatehuman$DASH$origlabelnum,$origlabelnum,$Savetime,$Barcode,$envnum,$NWKSaveSetID,$ExportDate,$expiredays,NOT-EXPIRED,$sizebytes,$StageingPath" >> $HOMEPATH/tools/$trackerfilex
		fi
	done
	sort -u $HOMEPATH/tools/$trackerfilex | grep -v "^Client Name" > $HOMEPATH/tools/$trackerfilex.srt1
#	echo "Client Name,Plug-IN,Orig BU Date,Label Number,Barcode,Env Number,NWK Save Set-ID,Orig Export Date,Remaining Retetion #Days,Expire-Status,Data Size Bytes,Staging Path" > $HOMEPATH/tools/$trackerfilex
	echo "Client Name,Plug-IN,Orig BU Date,Label Number,Savetime,Barcode,Env Number,NWK Save Set-ID,Orig Export Date,Remaining Retetion #Days,Expire-Status,Data Size Bytes,Staging Path" > $HOMEPATH/tools/$trackerfilex
	chmod 777 $HOMEPATH/tools/$trackerfilex >/dev/null 2>&1
	cat $HOMEPATH/tools/$trackerfilex.srt1 >> $HOMEPATH/tools/$trackerfilex
else
	echo "\n$RED_BG$WHITE_FG ERROR:$DEF$RED_FG Unable to stat metadata input file [$WHITE_FG$inputfile$RED_FG]$DEF"
	echo "$RED_FG Exitting ...$DEF"
	exit 1
fi
expired_="$(grep -c "EXPIRED" $HOMEPATH/tools/$clientx.dat)"
cat $clientx.dat | sort -u | grep -v EXPIRED > $HOMEPATH/tools/$clientx.dat2
cat $clientx.dat | sort -u | grep EXPIRED > $HOMEPATH/tools/$clientx.dat3

sort -r -k 5 $clientx.dat2 > $HOMEPATH/tools/$clientx.dat 
sort -r -k 5 $clientx.dat3 > $HOMEPATH/tools/$clientx.datx

echo "\n\n$GREEN_FG<<< ADMe Job Templates saved in$WHITE_FG [$clientx.dat]$GREEN_FG ... >>>$DEF"

echo "\n\tValid Job Count:\t\t $(grep -v "EXPIRED" $clientx.dat | wc -l |awk '{print $1}')"
echo "\tExpired Job Count:\t\t $expired_"
echo "\tDuplicate labelnum Count:\t $(grep -c "DUPLABEL" $clientx.dat)"
echo "\n$CYAN_FG View job templates?$WHITE_FG[Def=N Y=Yes X=Expired]$CYAN_FG: >$DEF $Asciesc"; read view
if [ "$view" = "Y" -o "$view" = "y" -o "$view" = "X" -o "$view" = "x" ]
then
	echo
	if [ "$view" = "Y" -o "$view" = "y" ]
	then
		grep -n "^" $clientx.dat | sed -n "s/:/: /"p
	elif [ "$view" = "X" -o "$view" = "x" ]
	then
		grep -n "^" $clientx.datx | sed -n "s/:/: /"p
	fi

	echo "\n=======================================================\n"
	if [ "$USECASE" = "avamar" ];then echo "$RED_FG Ensure this client account is defined on the target system:$WHITE_FG mccli client add --name=/ADME/$clientx$TAGX$DEF"; fi
	while true
	do
		lastline="$(wc -l $clientx.dat | awk '{print $1}')"
		echo "\n$CYAN_FG Choose by row number the job policy template to establish it or$WHITE_FG Q$CYAN_FG=Quit :>$DEF $Asciesc"; read job
		if [ "$job" -eq "Q" -o "$job" -eq "q" ];then break
		elif [ "$job" -gt "0" -a "$job" -le "$lastline" ] 
		then
			jobtemplate="$(sed -n "$job,$job"p $clientx.dat)"
			echo "\n$jobtemplate"
			echo "\n$CYAN_FG Establish Job Policy? Confirm Y or N $WHITE_FG[Def=N]$CYAN_FG: >$DEF $Asciesc"; read confirm
			if [ "$confirm" = "Y" -o "$confirm" = "y" ]
			then
				echo "$jobtemplate" > $HOMEPATH/tools/jobtemplate.sh; chmod 744 $HOMEPATH/tools/jobtemplate.sh; $HOMEPATH/tools/./jobtemplate.sh
				break
			fi
		fi
	done
fi
rm $HOMEPATH/tools/$clientx.dat2 $HOMEPATH/tools/$clientx.tmp $HOMEPATH/tools/clientx.csv $HOMEPATH/tools/tracker.s* $HOMEPATH/tools/jobtemplate.sh >/dev/null 2>&1
done
echo "\n$GREEN_FG<<< Script Completed >>>$DEF"
