#/bin/ksh
# Last update Nov 8th 2022 updated to handle newer korn shell

if [ -d /home/admin/admeadmin ]
then
	HOMEPATH="/home/admin/admeadmin"
else
	HOMEPATH="/atoadmin"
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
ClientList="$HOMEPATH/customize/unique-client-list.txt"

MetaDataList="$HOMEPATH/customize/aermetadata.final.csv"
echo -e "\nEnter complete path name to your AER metadata csv file or accept the default value.\n\n[Def=$MetaDataList]: > \c\r "; read filex
if [ "$filex" = "" ]
then
	echo -e "\nUsing AER metadata file name [$MetaDataList} ..."
else
	MetaDataList="$filex"
	echo -e "\nUsing AER metadata file name [$MetaDataList} ..."
fi

# MetaDataList="$HOMEPATH/customize/LIBB-aermetadata.csv"
Clientcsv="$HOMEPATH/customize/unique"
mkdir $Clientcsv

# Establish unique client list
# cat $MetaDataList | awk -F, '{print $17}' | awk -Favamar-client-hostname: '{print $2}' | awk '{print $1}' | sort -u | sed -n "s/\;//"gp > $ClientList
cat $MetaDataList | awk -F, '{print $17}' | awk -Ffullpath: '{print $2}' | awk '{print $1}' | sort -u | awk -F/ '{print $NF}' | sed -n "s/\;//"gp > $ClientList

# Create dedicated metadata csv files on a per client basis
lastline="$(wc -l $ClientList | awk '{print $1}')"
startline=1
totallinecnt=0
csv=".csv"
while true
do
        Clientx="$(sed -n "$startline,$startline"p $ClientList)"
        if [ "$startline" -gt "$lastline" ]
        then
                break
        else
                grep "$Clientx" $MetaDataList | grep -v "index" > $Clientcsv/$Clientx$csv
                clientlinecnt="$(wc -l $Clientcsv/$Clientx$csv | awk '{print $1}')"
                totallinecnt="$(expr $totallinecnt + $clientlinecnt)"
                echo "Processed Client name: $Clientx Line-Count: $clientlinecnt)"
                startline="$(expr $startline + 1)"
        fi
done
echo "Total Line Count: $totallinecnt"
