#!/bin/ksh
# Take a list of clients,domain names and place them into groups
# Clients must be of the same plugin type
grpentrycnt="5"
grpbasnam="vmimg"
grpnamsuffix="01"
grplist="grplist.dat"
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"
if [ -s /home/admin/admeadmin ]
then
	HOMEPATH="/home/admin/admeadmin"
else
	HOMEPATH="$HOMEPATH"
fi
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
# USer input data file
inputdatafile="$(head -1 /home/admin/admeadmin/tools/.inputdatafile)"

clear
echo "$GREEN_FG>>> autogroup.sh Version 19.71a 2023-03-31$DEF"
if [ "$1" = "" ]
then
        echo -e "\n$CYAN_FG Enter input file name sorted by client-name and formatted as:$WHITE_FG client-namex,domain-namex >$DEF $Asciesc>"; read ClientFile
 if [ "$ClientFile" = "" ]
        then
                echo "\nEnter a series of ClientX DomainX into the open vi file then save it :wq!:"
                rm buids_input.txt >/dev/null 2>&1
                vi buids_input.txt
                ClientFile="buids_input.txt"
        fi
else
        ClientFile="$1"
fi
# Save a copy of original file
orig=".orig"
echo -e "\n>>> Saving input file [$ClientFile] to [$ClientFile$orig]"
cp $ClientFile $ClientFile$orig > /dev/null 2>&1

# Ensure we're working with a csv file, copy/pastes from Excel will result in a tab between each field
echo -e ">>> Checking input file [$ClientFile] for csv format ..."
if [ "$(grep -c "," $ClientFile)" -eq "0" ]
then
	tmp1=".tmp1"
	echo -e "Converting input file [$ClientFile to csv format ...]\n"
	sed -n "s/	/,/"gp $ClientFile > $ClientFile$tmp1
	mv $ClientFile$tmp1 $ClientFile > /dev/null 2>&1
fi

# Ensure input file is sorted and contains no duplicate client names
echo -e ">>> Sorting input file [$ClientFile] and removing any duplicate client names ...\n"
xt1=".srt1"; ClientFile2="$ClientFile"
xt2=".srt2"; sort $ClientFile > $ClientFile$xt1
sort -u $ClientFile$xt1 > $ClientFile$xt2
mv $ClientFile$xt2 $ClientFile

if [ ! -s $ClientFile ]
then
        echo -e "\n$RED_FG Exiting ..., unable to stat your input file name [$ClientFile] $DEF\n"
	mv $ClientFile$orig $ClientFile
        exit
fi

# Learn default value passed from jobtemplate script, it will pass 4 arguments
# setup to provide a default value of the detected plugin type
#echo "DEBUG - 1st=$1 2nd=$2 3r=$3 4th=$4 5th=$5"
echo "$BLUE_BG$WHITE_FG NOTE: Press Enter at each prompt to accept its automated default value when appropriate$DEF"
if [ "$#" -eq "4" ]
then
	grptype="$3"; grpnum="$4"; grpbasnam="$grptype"
	if [ "$3" = "vmimg" ];then grpbasnam="1"
	elif [ "$3" = "winfs" ];then grpbasnam="2"
	elif [ "$3" = "lnxfs" ];then grpbasnam="3"
	elif [ "$3" = "unxfs" ];then grpbasnam="4"
	elif [ "$3" = "sql" ];then grpbasnam="5"
	elif [ "$3" = "ora" ];then grpbasnam="6"
	elif [ "$3" = "exch" ];then grpbasnam="7"
	elif [ "$3" = "hyper" ];then grpbasnam="8"
	elif [ "$3" = "ndmp" ];then grpbasnam="9"
	elif [ "$3" = "lotus" ];then grpbasnam="10"
	elif [ "$3" = "shpt" ];then grpbasnam="11"
	else grpbasnam="12"; fi
fi

# Interactive menu to choose an appropriate plugin naming convention
echo "$GREEN_FG"
echo "  1) vmimg   Plug-IN: VMimage"
echo "  2) winfs   Plug-IN: Windows FS"
echo "  3) lnxfs   Plug-IN: Linux FS"
echo "  4) unxfs   Plug-IN: Unix FS"
echo "  5) sql     Plug-IN: SQL"
echo "  6) ora     Plug-IN: Oracle"
echo "  7) exch    Plug-IN: Exchange VSS"
echo "  8) hyper   Plug-IN: Hyper-V VSS"
echo "  9) ndmp    Plug-IN: NDMP NAS"
echo " 10) lotus   Plug-IN: Lotus Notes"
echo " 11) shpt    Plug-IN: SharePoint VSS"
echo "$RED_FG 12) Non-Standard-Name$DEF"
echo -e "\n$DEF==================================================================="
echo -e "\n$CYAN_FG Enter$WHITE_FG Base-Group-Name$CYAN_FG value from above list.$WHITE_FG Enter Number-ID or$WHITE_FG Def=$grpbasnam$DEF > $Asciesc"; read input

# Based on interactive entry choose a plugin or if null accept the default predeifned above
if [ "$input" -eq "" ]
then
	grpbasnam="$grptype"
elif [ "$input" -eq "1" ];then grpbasnam="vmimg"
elif [ "$input" -eq "2" ];then grpbasnam="winfs"
elif [ "$input" -eq "3" ];then grpbasnam="lnxfs"
elif [ "$input" -eq "4" ];then grpbasnam="unxfs"
elif [ "$input" -eq "5" ];then grpbasnam="sql"
elif [ "$input" -eq "6" ];then grpbasnam="ora"
elif [ "$input" -eq "7" ];then grpbasnam="exch"
elif [ "$input" -eq "8" ];then grpbasnam="hyper"
elif [ "$input" -eq "9" ];then grpbasnam="ndmp"
elif [ "$input" -eq "10" ];then grpbasnam="lotus"
elif [ "$input" -eq "11" ];then grpbasnam="shpt"
elif [ "$input" -eq "12" ]
then
	basenamlength1="$(echo "$2" | wc | awk '{print $3}')"
	basenamlength="$(expr $basenamlength1 - 3)"
	grpbasnam="$(echo "$2" | cut -b 1-$basenamlength)"
	echo -e "\n$CYAN_FG Enter a$WHITE_FG Custom-Base-Group-Name$CYAN value or$WHITE_FG Enter$CYAN_FG to accept default value.$WHITE_FG Def=$grpbasnam$DEF > $Asciesc>"; read grpbasnam_

#	if [ "$grpbasnam_" = "" ];then grpbasnam_="$2"; fi
	if [ "$grpbasnam_" = "" ];then grpbasnam_="$(echo "$2" | cut -b 1-$basenamlength)"; fi

	lenx="$(expr $basenamlength + 2)"
	grpnum="$(echo "$2" | cut -b $(expr $basenamlength + 1)-$lenx)"
else
	grpbasname="$input"
        echo -e "\n$RED_FG Exiting ..., base name selection value is invlid$DEF\n"
	mv $ClientFile$orig $ClientFile > /dev/null 2>&1
	rm $ClientFile$xt1 $ClientFile$xt2 > /dev/null 2>&1 
        exit
fi

# figure out number of existing compatible group names and determine next sequential one
echo -e "\n$CYAN_FG Existing related group names:$WHITE_FG[$grpbasnam]$DEF\n"
group_list="$(awk -F, '{print $1}' $HOMEPATH/etc/admeclient.cfg | grep -v "^#" | sort -u | grep "^$grpbasnam")"
# display existing group list
echo "$group_list"
# next_group_count="$(echo "$group_list" | wc -l | awk '{print $1}')"
if [ "$group_list" = "" ];then next_group_count="0"; else next_group_count="$(echo "$group_list" | wc -l | awk '{print $1}')"; fi

if [ "$next_group_count" -ge "1" ];then next_group_count="$(expr $next_group_count + 1)"; else next_group_count="1"; fi

# Check if being called from jobtemplate script, use the passed value for the default
if [ "$#" -eq "4" ];then next_group_count="$grpnum"; fi

echo -e "\n$CYAN_FG Enter a numeric$WHITE_FG GROUP-NAME-SUFFIX$CYAN_FG value or$WHITE_FG Enter$CYAN_FG to accept default value$WHITE_FG 1-99 or Def=[$next_group_count]$DEF > $Asciesc"; read grpnamsuffix

if [ "$grpnamsuffix" -eq "" ];then grpnamsuffix="$next_group_count"; fi

if [ "$grpnamsuffix" -lt "1" -o "$grpnamsuffix" -gt "99" ]
then
        echo -e "\n$RED_FG Exiting ..., group suffix value must be in range of 1 - 99 $DEF\n"
	mv $ClientFile$orig $ClientFile > /dev/null 2>&1
	rm $ClientFile$xt1 $ClientFile$xt2 > /dev/null 2>&1 
        exit
elif [ "$grpnamsuffix" -lt "10" ]
then
	if [ "$(echo "$grpnamsuffix" | cut -b 1)" -ne "0" ];then grpnamsuffix="0$grpnamsuffix"; else grpnamsuffix="$grpnamsuffix"; fi
fi

if [ "$(grep -c "^$grpbasnam$grpnamsuffix," $HOMEPATH/etc/admeclient.cfg)" -gt "0" ]
then
	echo -e "\n$RED_BG$WHITE_FG WARNING: $DEF$RED_FG Group name$WHITE_FG [$grpbasnam$grpnamsuffix]$DEF$RED_FG already exists.\n"
	echo -e " 	   If you choose to override this warning the existing group will be overwritten"
	echo -e "           resulting in its staging path and export policy fields being modified"
	echo -e "\n$CYAN_FG Enter Y or N to continue: $WHITE_FG[Def=N]$DEF: > $Asciesc"; read warning
	if [ "$warning" = "Y" -o "$warning" = "y" ]
	then
		echo -e "\n$GREEN_FG Override accepted:..."
		egrep -v "^$grpbasnam$grpnamsuffix,|:$grpbasnam" $HOMEPATH/etc/admeclient.cfg > $HOMEPATH/etc/admeclient.cfgtmp
		mv $HOMEPATH/etc/admeclient.cfgtmp $HOMEPATH/etc/admeclient.cfg
	else
		echo -e "\n$RED_FG Exitting ...$DEF"
		mv $ClientFile$orig $ClientFile > /dev/null 2>&1
		rm $ClientFile$xt1 $ClientFile$xt2 > /dev/null 2>&1 
        	exit
	fi
fi

defclientcount="$(wc -l $ClientFile | awk '{print $1}')"
if [ "$#" -eq "4" ]
then
	echo -e "\n$CYAN_FG Enter desired$WHITE_FG NUMBER-OF-CLIENTS$CYAN_FG allowed in group name or$WHITE_FG Enter$CYAN_FG to accept default value$WHITE_FG [$grptype$grpnum Def=$defclientcount]:$DEF > $Asciesc"; read grpentrycnt
else
echo -e "\n$CYAN_FG Enter desired$WHITE_FG NUMBER-OF-CLIENTS$CYAN_FG allowed in group name or$WHITE_FG Enter$CYAN_FG to accept default value$WHITE_FG [$grpbasnam$grpnamsuffix Def=$defclientcount]:$DEF > $Asciesc"; read grpentrycnt
fi
if [ "$grpentrycnt" -gt "200" ]
then
        echo -e "\n$RED_FG Exiting ..., maximum client count per group out of range$DEF\n"
	mv $ClientFile$orig $ClientFile > /dev/null 2>&1
	rm $ClientFile$xt1 $ClientFile$xt2 > /dev/null 2>&1 
        exit
elif [ "$grpentrycnt" -eq "" ]
then
	grpentrycnt="$defclientcount"
fi

# cat $grplist


if [ -s .autogroup-type.dat ];then pathxdef="$(head -1 .autogroup-type.dat)"; else  pathxdef=1; fi
echo -e "\n$GREEN_FG 1) Windows Path for Tapeout"
echo -e " 2) Windows Path for ADS to DD"
echo -e " 3) Unix-Linux Path for Tapeout"
echo -e " 4) Unix-Linux Path for ADS to DD"
echo -e " 5) Windows Path for PPDM"
echo -e " 6) Unix-Linux Path for PPDM"
echo -e "\n$DEF==================================================================="
while true
do
# ====> Check plugin and use case are compatible with default option value here
	expectedplugin="$(grep "$grpbasnam$grpnamsuffix" $inputdatafile| head -1 | awk -F, '{print $NF}')"
	expectedads="$(grep "$grpbasnam$grpnamsuffix" $inputdatafile | head -1 | awk -F, '{print $3}' | grep -c "-")"

	if [ "$(egrep -c "5|6" $HOMEPATH/tools/.autogroup-type.dat)" -ne "0" ];then expectedppdm="1"; fi

	paxit="$(grep "$grpbasnam$grpnamsuffix" $inputdatafile| head -1 | grep -c "archive pax")"
	if [ "$(echo "$expectedplugin" | egrep -c "^30|^1016")" -gt "0" -a "$paxit" -eq "0" ];then pluginx="windows"
	else pluginx="linux"; fi
	
	if [ "$expectedads" -gt "0" ];then ads="ads"; else ads="tape"; fi
	if [ "$expectedppdm" -gt "0" ];then ads="ppdm"; else ads="tape"; fi

#	if [ "$ads" = "tape" -a "$pluginx" = "windows" ];then pathxdef=1
#	elif [ "$ads" = "ads" -a "$pluginx" = "windows" ];then pathxdef=2
#	elif [ "$ads" = "tape" -a "$pluginx" = "linux" ];then pathxdef=3
#	elif [ "$ads" = "ads" -a "$pluginx" = "linux" ];then pathxdef=4
#	elif [ "$ads" = "ppdm" -a "$pluginx" = "windows" ];then pathxdef=5
#	elif [ "$ads" = "ppdm" -a "$pluginx" = "linux" ];then pathxdef=6;fi

	pathxdef="$(head -1 $HOMEPATH/tools/.autogroup-type.dat | awk '{print $1}')"

	echo -e "\n$BLUE_BG$WHITE_FG Note: $DEF VMimage groups default to use a Windows staging path. For a Linux staging path, manually override with appropriate option.\n"
	echo -e "\n$CYAN_FG Choose$WHITE_FG BASE-STAGING-PATH$CYAN_FG option from above list. Enter Number-ID or$WHITE_FG Enter$CYAN_FG to accept default value $WHITE_FG Def=$pathxdef$DEF > $Asciesc"; read pathx
	if [ "$pathx" -eq "" ];then pathx="$pathxdef"
	elif [ "$pathx" -lt "1" -o "$pathx" -gt "6" ]
	then
        	echo -e "\n$RED_FG Base staging value was invalid$DEF\n"
		mv $ClientFile$orig $ClientFile > /dev/null 2>&1
		rm $ClientFile$xt1 $ClientFile$xt2 > /dev/null 2>&1 
        	continue
	elif [ "$pathx" -eq "1" ];then echo "1" > autogroup-type.dat
	elif [ "$pathx" -eq "2" ];then echo "2" > autogroup-type.dat
	elif [ "$pathx" -eq "3" ];then echo "3" > autogroup-type.dat
	elif [ "$pathx" -eq "4" ];then echo "4" > autogroup-type.dat
	elif [ "$pathx" -eq "5" ];then echo "5" > autogroup-type.dat
	elif [ "$pathx" -eq "6" ];then echo "6" > autogroup-type.dat; fi
	echo "$pathx" > .autogroup-type.dat
	break
done

if [ "$pathx" -eq "1" -o "$pathx" -eq "2" -o "$pathx" -eq "5" ]
then
	if [ -s $grplist ]
	then
		drvx="$(grep "^$grptype$grpnum" $grplist | head -1 | awk '{print $3}' | awk -F\- '{print $2}')"
	else
		drvx="X"	
	fi
	while true
	do
		echo -e "\n$CYAN_FG Enter a Windows staging drive letter. [$WHITE_FG Def=$drvx$DEF ] : > $Asciesc"; read dpathx_
		if [ "$dpathx_" = "" ];then dpathx_="$drvx"; fi

		if [ "$drvx" = "" ]
		then
			echo -e "\n$RED_FG ERROR: A valid staging drive letter must be defined$DEF"
		else
			break
		fi
	done
else
	mountpt="$(grep "^$grptype$grpnum" $grplist | head -1 | awk '{print $3}')"
	mountpt="$(grep "$grptype$grpnum" $grplist | head -1 | awk '{print $3}')"
	while true
	do
		echo -e "\n$CYAN_FG Enter a Linux staging mount point. [$WHITE_FG Def=$mountpt$DEF] : > $Asciesc"; read dpathx_
		if [ "$dpathx_" = "" ];then dpathx_="$mountpt"; fi
		if [ "$mountpt" = "" ]
		then
			echo -e "\n$RED_FG ERROR: A valid Unix/Linux staging mount point path must be defined$DEF"
		else
			break
		fi
	done
fi


if [ "$(grep "$grpbasnam$grpnamsuffix" $inputdatafile | grep -c "-expire " )" -ne "0" ];then Expire="/Expiry-Date-EXPIRE"; else EXPIRE="";fi

if [ "$pathx" -eq "1" ]
then
	dpathx="$dpathx_:/ADME"; fld12="ADME_Full"
# echo "DEBUG - dpathx=$dpathx Expire=$Expire grpbasnam=$grpbasnam grpnamsuffix=$grpnamsuffix"
	fld10="$dpathx$Expire/$grpbasnam$grpnamsuffix"; fld13="-p ADME -w Y$grpbasnam$grpnamsuffix"; fld14="-p ADME -w $grpbasnam$grpnamsuffix"
elif [ "$pathx" -eq "2" ]
then
	dpathx="$dpathx_:/ADME"; fld13="n/a"; fld14="n/a" 
	fld10="$dpathx$Expire/$grpbasnam$grpnamsuffix"; fld12="--expires=365"
elif [ "$pathx" -eq "3" ]
then
	dpathx="$dpathx_"; fld12="ADME_Full"
	fld10="$dpathx/$grpbasnam$grpnamsuffix"; fld13="-p ADME -w Y$grpbasnam$grpnamsuffix"; fld14="-p ADME -w $grpbasnam$grpnamsuffix"
elif [ "$pathx" -eq "4" ]
then
	dpathx="$dpathx_"; fld13="n/a"; fld14="n/a" 
	fld10="$dpathx/$grpbasnam$grpnamsuffix"; fld12="--expires=365"
elif [ "$pathx" -eq "5" ]
then
	if [ "$(grep -c "tpolicy" $inputdatafile)" -eq "0" ]
	then
		if [ -s $HOMEPATH/customize/ppdm.cfg ];then fld12="$(grep "^WIN:" $HOMEPATH/customize/ppdm.cfg | awk -F: '{print $2}' | sed -n "s/~/-/"gp)"; fi
	else fld12="n/a"; fi
	dpathx="$dpathx_:/ADME"; fld13="n/a"; fld14="n/a" 
	fld10="$dpathx/$grpbasnam$grpnamsuffix"
elif [ "$pathx" -eq "6" ]
then
	if [ "$(grep -c "tpolicy" $inputdatafile)" -eq "0" ]
	then
		if [ -s $HOMEPATH/customize/ppdm.cfg ];then fld12="$(grep "^LNX:" $HOMEPATH/customize/ppdm.cfg | awk -F: '{print $2}' | sed -n "s/~/-/"gp)"; fi
	else fld12="n/a"; fi
	dpathx="$dpathx_"; fld13="n/a"; fld14="n/a" 
	fld10="$dpathx/$grpbasnam$grpnamsuffix" 
fi

echo -e "\n Using staging path [$fld10]"
# echo -e "\n Using staging path [$dpathx/$Expire/$grpbasnam$grpnamsuffix]"

echo -e "\n$CYAN_FG Confirm whether to prompt as each individual client is added to a group: Y or N$WHITE_FG [Def=N]$DEF > $Asciesc"; read input
if [ "$input" = "y" -o "$input" = "Y" ];then cconfirm=1; else cconfirm=0; fi

echo -e "\n$CYAN_FG Confirm whether to prompt for confirmation when a new group is being established: Y or N$WHITE_FG [Def=Y]$DEF > $Asciesc"; read input
if [ "$input" = "n" -o "$input" = "N" ];then gconfirm=0; else gconfirm=1; fi

echo -e "\n$CYAN_FG Confirm whether to make a copy of the current admeclient.cfg file: Y or N$WHITE_FG [Def=N]$DEF > $Asciesc"; read input
if [ "$input" = "y" -o "$input" = "Y" ]
then
        fileprefix="$(date +'20%y-%m-%d-%M-%S')"
        echo -e ">>> Saved-File-Name: $HOMEPATH/etc/$fileprefix-admeclient.cfg"
        cp $HOMEPATH/etc/admeclient.cfg $HOMEPATH/etc/$fileprefix-admeclient.cfg
fi

echo -e "\n$BLUE_BG$WHITE_FG User Input Summary: Group-Name=$grpbasnam Group-Name-Suffix=$grpnamsuffix Client-Count-Per-group=$grpentrycnt $DEF"
while true
do
	echo "\n$RED_BG$WHITE_FG Final confirmation, Must Confirm it is okay to proceed$DEF$WHITE_FG Y or N >$DEF $Asciesc"; read input
	if [ "$input" = "n" -o "$input" = "N" ]
	then
		mv $ClientFile$orig $ClientFile > /dev/null 2>&1
		rm $ClientFile$xt1 $ClientFile$xt2 > /dev/null 2>&1 
		exit
	elif [ "$input" = "" ];then continue
	elif [ "$input" = "y" -o "$input" = "Y" ]; then break; fi
done

linecnt="$(wc -l "$ClientFile" | awk '{print $1}')"
linex="1"; grpcnxt=0
while true
do
        clientx="$(sed -n "$linex,$linex"p $ClientFile | awk -F, '{print $1}')"
        domainx="$(sed -n "$linex,$linex"p $ClientFile | awk -F, '{print $2}')"
#        echo "Client-Entry: Grp-Name=$grpbasnam$grpnamsuffix Domain-Name=$domainx Client-Name=$clientx"
        if [ "$cconfirm" -eq "1" ]
        then
                echo "<<<< CONFIRM - Press Enter to Continue >>>> $Asciesc "; read
                adme  -clientx addclient "fld1=$grpbasnam$grpnamsuffix,fld4=$domainx,fld5=$clientx,fld6=,fld7=,fld8=,fld10=$wpathx/$Expire$grpbasnam$grpnamsuffix,fld12=$fld12,fld13=$fld13,fld14=$fld14,fld15=,fld16=,fld17=,fld18=" 2>/dev/null
        else
                adme  -clientx addclient "fld1=$grpbasnam$grpnamsuffix,fld4=$domainx,fld5=$clientx,fld6=,fld7=,fld8=,fld10=$fld10,fld12=$fld12,fld13=$fld13,fld14=$fld14,fld15=,fld16=,fld17=,fld18=" 2>/dev/null
        fi

        linex="$(expr "$linex" + 1)"
        if [ "$linex" -gt "$linecnt" ];then break; fi
        grpcnt="$(expr $grpcnt + 1 )"

        if [ "$grpcnt" -ge "$grpentrycnt" ]
        then
                grpcnt="0"
                grpnamsuffix="$(expr $grpnamsuffix + 1)"
                if [ "$grpnamsuffix" -le "9" ];then grpnamsuffix="0$grpnamsuffix"; fi
                if [ "$gconfirm" -eq "1" ]
                then
                        echo -e "\n$RED_FG Confirm okay to start a new group name:$WHITE_FG [$grpbasnam$grpnamsuffix] Must Enter Y or N > $Asciesc$DEF"; read input2
                        if [ "$input2" = "N" -o "$input2" = "n" ];then exit;fi
                fi
        fi
done
$HOMEPATH/tools/autoverify.sh $1
# Cleanup 
mv $ClientFile$orig $ClientFile > /dev/null 2>&1
rm $ClientFile$xt1 $ClientFile$xt2 > /dev/null 2>&1 
echo -n "<<< Script Complete >>>"
