#!/bin/ksh
# Upgrade script for ADMe using admin path
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"

echo "\n$CYAN_FG Upgrade Script Version:$WHITE_FG 19.68 2022-12-12 $DEF"
userx="$(id)"; activemove=0
BULOCATION="/home/admin/admeadmin"

# The upgrade process checks to see if /atoadmin the original install path exists
if [ ! -d /atoadmin ]
then
	if [ "$(echo "$(id)" | grep -c "root")" -ne "1" ]
	then
		echo -e "$RED_BG$WHITE_FG WARNING: $DEF You must be logged in as root to perform an ADMe upgrade, Exitting ..."
		exit 1
	fi
# ====> Fresh install start out in proper folder for admin path
	echo -e "\n$GREEN_FG UPGRADE-Step-1A:$DEF No historical [/atoadmin] installation detected, using default path /home/admin/admeadmin"
	BULOCATION="/home/admin/admeadmin"
elif [ -s $BULOCATION/.adminmovecomplete ]
then
# ====> Already on code supporting use of admin path, get BULOCATION details from env-1 file
	echo -e "\n$GREEN_FG UPGRADE-Step-1B:$DEF A historical installation detected in [/atoadmin] however a copy from it was performed previously."
	BULOCATION="$(grep "^BULOCATION=" /home/admin/admeadmin/etc/atoenv.cfg | tail -1 | awk -F= '{print $2}')"
elif [ ! -s $BULOCATION/.adminmovecomplete -a -d /atoadmin ]
then
# ====> Still on root code, need to move everything from /atoadmin to new install path /home/admin/admeadmin
	echo -e "\n$GREEN_FG UPGRADE-Step-1C:$DEF Copying from historical install path [/atoadmin] to new install path [/home/admin/admeadmin] ..."
	if [ "$(echo "$userx" | grep -c "root")" -ne "1" ]
	then
		echo -e "\n$RED_FG ERROR:$DEF You must be [root] in order to execute UPGRADE-Step-1C, Exitting ..."
		exit 1
	fi
	mkdir $BULOCATION > /dev/null 2>&1; chmod 770 $BULOCATION > /dev/null 2>&1
	cp -rp /atoadmin/* $BULOCATION > /dev/null 2>&1
# ====> Clean up old builds 
	rm -rf $BULOCATION/adme.war $BULOCATION/adme-1.0.50.war $BULOCATION/adme-tar-45* $BULOCATION/1 $BULOCATION/... $BULOCATION/.... $BULOCATION/atoupgrade.sh >/dev/null 2>&1
	date > $BULOCATION/.adminmovecomplete
	mv /atoadmin/.atoupgrade.dat $BULOCATION/.admeupgrade.dat > /dev/null 2>&1
	rm $BULOCATION/.$BULOCATION/.atoupgrade.dat >/dev/null 2>&1

	rm -rf /tmp/initiate* /tmp/ato* /tmp/admmenu.lck /tmp/admemotd >/dev/null 2>&1


# This code is to move from root to admin crontab, mothballed until ew get corntab -u admin to work
#	echo -n ">>> Transferring ADMe related CRON entries from root to admin CRON ..."
# ====> Ensure no ADMe entries exist in admin CRON (there shouldn;t be any)
#	crontab -u admin -l | egrep -v "ADMe|admbatch" > $BULOCATION/tmp/.crondat
# ====> Get ADMe related cron entries from root CRON
#	crontab -l | egrep "ADMe|admbatch" >> $BULOCATION/tmp/.crondat 2>&1
# ====> Update & apply admin CRON
#	crontab -u admin $BULOCATION/tmp/.crondat 2>&1
# ====> remove ADMe related entries from root CRON
#	crontab -u root -l | egrep -v "ADMe|admbatch" > $BULOCATION/tmp/.crondatroot
#	crontab -u root $BULOCATION/tmp/.crondatroot	
#	rm -rf $BULOCATION/tmp/.crondat $BULOCATION/tmp/.crondatroot 2>&1

	activemove=1
else
	echo -e "\n$RED_FG ERROR:$DEF Unable to determine current install status, Exitting ..."
	exit 1
fi
# Catch all, ensure BULOCATION is updated accordingly
if [ "$BULOCATION" = "" ];then BULOCATION="/home/admin/admeadmin"; fi

# Directories under install folder will be established by ADME but when upgrading to a newer version
# some net new folders may be required, check to ensure theyare all established.

echo -e "\n$GREEN_FG UPGRADE-Step-2:$DEF Verifying ADMe directory structure is in place... "
if [ ! -d $BULOCATION/etc ];then mkdir $BULOCATION/etc; fi
if [ ! -d $BULOCATION/log ];then mkdir $BULOCATION/log; fi
if [ ! -d $BULOCATION/doc ];then mkdir $BULOCATION/doc; fi
if [ ! -d $BULOCATION/health ];then mkdir $BULOCATION/health; fi
if [ ! -d $BULOCATION/tmp ];then mkdir $BULOCATION/tmp; fi
if [ ! -d $BULOCATION/scripts ];then mkdir $BULOCATION/scripts; fi
if [ ! -d $BULOCATION/customize ];then mkdir $BULOCATION/customize; fi
if [ ! -d $BULOCATION/backups ];then mkdir $BULOCATION/backups; fi
if [ ! -d $BULOCATION/grabs ];then mkdir $BULOCATION/grabs; fi
if [ ! -d $BULOCATION/stats ];then mkdir $BULOCATION/stats; fi
if [ ! -d $BULOCATION/jobstats ];then mkdir $BULOCATION/jobstats; fi
if [ ! -d $BULOCATION/audit ];then mkdir $BULOCATION/audit; fi
if [ ! -d $BULOCATION/tools ];then mkdir $BULOCATION/tools; fi

# OLD code here no longer used
# check for existence of various custom flag files and if present move them into new cutomize folder
# custom flag files are no longer used for general ADMe customization
# if [ ! -d $BULOCATION/customize ];then mkdir $BULOCATION/customize; fi

# disable maint check for menu transitions, user can renable if they choose 
# if [ ! -f $BULOCATION/customize/skipit2.txt ];then touch $BULOCATION/customize/skipit2.txt; fi
# if [ -f $BULOCATION/recapture.txt ];then mv $BULOCATION/recapture.txt $BULOCATION/customize/recapture.txt; else touch $BULOCATION/customize/recapture.txt; fi
# if [ -f $BULOCATION/atooracle.txt ];then mv $BULOCATION/atooracle.txt $BULOCATION/customize/admeoracle.txt; fi
# if [ -f $BULOCATION/arcserv_custom.txt ];then mv $BULOCATION/arcserv_custom.txt $BULOCATION/customize/arcserv_custom.txt; fi

# if [ -f $BULOCATION/networker.bug1 ];then mv $BULOCATION/networker.bug1 $BULOCATION/customize/networker.bug1; fi
# if [ ! -f $BULOCATION/customize/networker.bug1 ];then echo "-o \"vss:*=off\"" > $BULOCATION/customize/networker.bug1; fi
# if [ ! -f $BULOCATION/customize/networker.txt ];then echo "PROBE=Y\"" > $BULOCATION/customize/networker.txt; fi

# if [ -f $BULOCATION/vmimage_domains.txt ];then mv $BULOCATION/vmimage_domains.txt $BULOCATION/customize/vmimage_domains.txt; fi
# if [ -f $BULOCATION/commvault.pwd ];then mv $BULOCATION/commvault.pwd $BULOCATION/customize/commvault.pwd; fi
# if [ -f $BULOCATION/tapescriptbu.txt ];then mv $BULOCATION/tapescriptbu.txt $BULOCATION/customize/tapescriptbu.txt; fi
# if [ -f $BULOCATION/nopurge.txt ];then mv $BULOCATION/nopurge.txt $BULOCATION/customize/nopurge.txt; fi

# Ensure any existing env files have control file paths updated to new location
rm $BULOCATION/tmp/atoenv.cfg $BULOCATION/tmp/atoenv.num >/dev/null 2>&1
echo -e "\n$GREEN_FG UPGRADE-Step-3:$DEF Verifying existing Env files support use of admin account\n"
for x in $(echo "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30")
do
        if [ "$x" -eq "1" ];then x=""; fi
        if [ ! -s $BULOCATION/etc/atoenv.cfg$x ]; then continue; fi
	echo ">>> Processing file Env-$x"
        grep -n "^" $BULOCATION/etc/atoenv.cfg$x | sed -n "s/:/ /"p > $BULOCATION/tmp/atoenv.num
        ln1="$(grep "ATO CONTROL FILES" $BULOCATION/tmp/atoenv.num | awk '{print $1}')"
        ln2="$(grep "PSEUDOCLIENT=" $BULOCATION/tmp/atoenv.num | awk '{print $1}')"
        sed -n "1,$ln1"p $BULOCATION/etc/atoenv.cfg$x > $BULOCATION/tmp/atoenv.cfg
#        echo "CFG=$BULOCATION/etc/atoclient.cfg" >> $BULOCATION/tmp/atoenv.cfg
        echo "CFG=$BULOCATION/etc/admeclient.cfg" >> $BULOCATION/tmp/atoenv.cfg
        echo "LOG=$BULOCATION/log/atoevent.log$x" >> $BULOCATION/tmp/atoenv.cfg
        echo "TMP_PATH=$BULOCATION/tmp/atocfg$x" >> $BULOCATION/tmp/atoenv.cfg
        sed -n "$ln2,99"p $BULOCATION/etc/atoenv.cfg$x >> $BULOCATION/tmp/atoenv.cfg
        mv $BULOCATION/tmp/atoenv.cfg $BULOCATION/etc/atoenv.cfg$x >/dev/null 2>&1

	grep -n "^" $BULOCATION/etc/atoenv.cfg$x | sed -n "s/:/ /"p > $BULOCATION/tmp/atoenv.num
        ln1="$(grep "BYDATEPATHXTN=" $BULOCATION/tmp/atoenv.num | awk '{print $1}')"
        ln2="$(grep "DEFSTAGELOC=" $BULOCATION/tmp/atoenv.num | awk '{print $1}')"
        sed -n "1,$ln1"p $BULOCATION/etc/atoenv.cfg$x > $BULOCATION/tmp/atoenv.cfg
        echo "BULOCATION=/home/admin/admeadmin" >> $BULOCATION/tmp/atoenv.cfg
        sed -n "$ln2,99"p $BULOCATION/etc/atoenv.cfg$x >> $BULOCATION/tmp/atoenv.cfg
        mv $BULOCATION/tmp/atoenv.cfg $BULOCATION/etc/atoenv.cfg$x >/dev/null 2>&1

#	/usr/local/avamar/bin/adme $x -env autoedit 'LINUXSS=DO-NOT-USE BULOCATION=/home/admin/admeadmin' >/dev/null 2>&1
done
if [ -s $BULOCATION/etc/atoclient.cfg ];then mv $BULOCATION/etc/atoclient.cfg $BULOCATION/etc/admeclient.cfg >/dev/null 2>&1; fi
rm $BULOCATION/tmp/atoenv.cfg $BULOCATION/tmp/atoenv.num >/dev/null 2>&1

# This section used to add new variables into existing env files when required
# variable format, space separate between var's: variable-name=def-value^ref-variable-name
# ref variable names used to position new variable next to it
# newenvvariables="SCRIPT_TIMEOUT=36000^COLORSCHEME= SCRIPT_TIMEOUT2=35002^LOG
# mail_from=$(grep admin_mail_sender /usr/local/avamar/var/mc/server_data/prefs/mcserver.xml | awk -F\" '{print $4}')
# if [ "$mail_from" = "" ];then mail_from="n/a"; fi

mail_from="ADME-Admin@$(hostname -d)"
echo -e "\n$GREEN_FG UPGRADE-Step-4:$DEF Checking for any new environment file variables required"
# newenvvariables="SCRIPT_TIMEOUT=36000^COLORSCHEME= MYEDITOR=/bin/vi^COLORSCHEME= MAIL_FROM=$mail_from^MAIL_TO BULOCATION=$BULOCATION^MYEDITOR= BYDATEPATHXTN=N^MYEDITOR= ARCHIVEUTIL=gzip^COLORSCHEME= DEFSTAGELOC=F:/tapeout^BULOCATION "
# newenvvariables="SCRIPT_TIMEOUT=36000^COLORSCHEME= ARCHIVEUTIL=gzip^COLORSCHEME= "
newenvvariables="MAIL_TO_ERROR=^MAIL_TO= USER_COMMENT=No-Comment^MAIL_FROM= USE_DATADOMAIN=Y^ARCHIVEUTIL= "
for x in $(echo "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30")
do
	if [ "$newenvvariables" = "" ];then break; fi
	if [ "$x" -eq "1" ];then x=""; fi
	if [ ! -s $BULOCATION/etc/atoenv.cfg$x ]; then continue; fi
	for y in $(echo "$newenvvariables")
	do
		varname="$(echo "$y" | awk -F^ '{print $1}' | awk -F= '{print $1}')"
		varx="$(echo "$y" | awk -F^ '{print $1}')"
		ref="$(echo "$y" | awk -F^ '{print $2}')"
		if [ "$(grep -c "^$varname="  $BULOCATION/etc/atoenv.cfg$x)" -ne "0" ];then continue; fi
		grep -n "^" $BULOCATION/etc/atoenv.cfg$x | sed -n "s/:/ /"p > /tmp/atoenv.cfg$x
		linex="$(grep " $ref" /tmp/atoenv.cfg$x | awk '{print $1}')"
		sed -n "1,$linex"p $BULOCATION/etc/atoenv.cfg$x > /tmp/atoenv.cfg$x.tmp
		echo "$varx" >> /tmp/atoenv.cfg$x.tmp
		sed -n "$(expr $linex + 1),99"p $BULOCATION/etc/atoenv.cfg$x >> /tmp/atoenv.cfg$x.tmp
  		mv /tmp/atoenv.cfg$x.tmp $BULOCATION/etc/atoenv.cfg$x
 		rm /tmp/atoenv.cfg$x >/dev/null 2>&1
	done
done

# rename job logs and config files from ato to adm, the e is not included to retain the same column width
for a in $(echo "etc log")
do
        for x in $(ls -rtl $BULOCATION/$a/atobatch-*.* 2>/dev/null)
        do
                if [ "$(echo "$x" | grep -c "atobatch")" -ne "0" ]
                then
                        filex="$(echo "$x" | sed -n "s/atobatch/admbatch/"p)"
                        mv $x $filex >/dev/null 2>&1
                fi
        done
done

# rename the existing backup files
for a in $(echo "backups")
do
        for x in $(ls -rtl $BULOCATION/$a/atoback* 2>/dev/null)
        do
                if [ "$(echo "$x" | grep -c "atoback")" -ne "0" ]
                then
                        filex="$(echo "$x" | sed -n "s/atoback/admeback/"p)"
                        mv $x $filex > /dev/null 2>&1
                fi
        done
done

# rename the existing grab files
for a in $(echo "grabs")
do
        for x in $(ls -rtl $BULOCATION/$a/atograb* 2>/dev/null)
        do
                if [ "$(echo "$x" | grep -c "atograb")" -ne "0" ]
                then
                        filex="$(echo "$x" | sed -n "s/atograb/admegrab/"p)"
                        mv $x $filex >/dev/null 2>&1
                fi
        done
done

# adjust existing bulk profile contents from ato to adme, names already modified above
Files="$(ls -rtl $BULOCATION/etc/admbatch-*.cfg 2>/dev/null | awk '{print $NF}' 2>/dev/null)"
for x in $Files
do
        if [ $(grep -c "^Select_Flags" $x) -eq 0 ]
        then
                if [ $(head -1 $x | grep -c "^FAIL") -eq 0 ]
                then
                        echo "FAIL ACTION STOP" > /tmp/batch.tmp
                fi
                sed "s/atob/admb/" $x | sed "s/ato/adme/" >> /tmp/batch.tmp
                mv /tmp/batch.tmp $x >/dev/null 2>&1
        else
                continue
        fi
done

# rename Tapeout_Flags line to Migration_Flags in all job policies
Files="$(ls -rtl $BULOCATION/etc/admbatch-*.cfg  2>/dev/null | awk '{print $NF}' 2>/dev/null)"
for x in $Files
do
        if [ $(grep -c "Tapeout_Flags" $x) -ne 0 ]
        then
                sed "s/Tapeout_Flags/Migration_Flags/" $x > /tmp/tapouetflags.tmp
                mv /tmp/tapouetflags.tmp $x >/dev/null 2>&1
        else
                continue
        fi
done

# ensure pseudo client name ADMEbackups is present used to retain ADMe backups of itself to
echo -e "\n$GREEN_FG UPGRADE-Step-5:$DEF Verifying presence of /ADME/ADMEbackups account..."
if [ "$(/usr/local/avamar/bin/avmgr getm --account=/ADME | grep -c ADMEbackups)" -eq "0" ]
then
	/usr/local/avamar/bin/mccli client add --name=/ADME/ADMEbackups >/dev/null 2>&1
fi

if [ -s $BULOCATION/log/atoaudit.log ]
then
	mv $BULOCATION/log/atoaudit.log $BULOCATION/audit/oldformat_atoaudit.log >/dev/null 2>&1
fi

echo -e "\n$GREEN_FG UPGRADE-Step-6:$DEF Refreshing ADMe Credentials, this can take some time Please Wait ..."
/usr/local/avamar/bin/adme -securityrefresh noprompt >/dev/null 2>&1
# /usr/local/avamar/bin/adme -securityrefresh noprompt

echo -e "\n$GREEN_FG UPGRADE-Step-7:$DEF Updating Scratch Environment File-20"
/usr/local/avamar/bin/adme 20 -env autoedit 'USER_COMMENT=RESERVED-DO-NOT-USE' >/dev/null 2>&1

echo -e "\n$GREEN_FG UPGRADE-Step-8:$DEF Refreshing Environment file discovery"
rm -rf $BULOCATION/jobstats/.envrefresh.lck >/dev/null 2>&1
/usr/local/avamar/bin/adme -env report >/dev/null

echo -e "\n$GREEN_FG UPGRADE-Step-9:$DEF Refreshing domain/client discovery Please wait ..."
# /usr/local/avamar/bin/adme -cfg refresh >/dev/null
/usr/local/avamar/bin/adme -cfg refresh

echo -e "\n$GREEN_FG UPGRADE-Step-10:$DEF Define SMTP relay to mailx for mail notifications ..."
if [ "$(grep -c "^set smtp=" /etc/mail.rc)" -eq "0" ]
then
	echo "\nConfigure SMTP relay in /etc/mail.rc"
	smtprelay="$(grep smtp /usr/local/avamar/var/mc/server_data/prefs/mcserver.xml | awk -Fvalue= '{print $2}' | awk -F\" '{print $2}')"
	echo -e "\nset smtp=$smtprelay" >> /etc/mail.rc
fi

echo -e "\n$GREEN_FG UPGRADE-Step-11:$DEF Refreshing paths defined in webui.txt to support admin account ..."
grep -v "atoadmin" $BULOCATION/customize/webui.txt > $BULOCATION/tmp/webui.tmp1 
sed -n "s/atoadmin/home\/admin\/admeadmin/"gp $BULOCATION/customize/webui.txt >> $BULOCATION/tmp/webui.tmp1
mv $BULOCATION/tmp/webui.tmp1 $BULOCATION/customize/webui.txt >/dev/null 2>&1

# Ensure latest adme.war is available to correct security issue 52 or higher
rm -rf $BULOCATION/tmp/webapp >/dev/null 2>&1

if [ -s $BULOCATION/adme-1.0.70.war ];then cp $BULOCATION/adme-1.0.70.war $BULOCATION/adme.war
elif [ -s $BULOCATION/adme-1.0.69.war ];then cp $BULOCATION/adme-1.0.69.war $BULOCATION/adme.war
elif [ -s $BULOCATION/adme-1.0.68.war ];then cp $BULOCATION/adme-1.0.68.war $BULOCATION/adme.war
elif [ -s $BULOCATION/adme-1.0.67.war ];then cp $BULOCATION/adme-1.0.67.war $BULOCATION/adme.war
elif [ -s $BULOCATION/adme-1.0.66.war ];then cp $BULOCATION/adme-1.0.66.war $BULOCATION/adme.war
elif [ -s $BULOCATION/adme-1.0.65.war ];then cp $BULOCATION/adme-1.0.65.war $BULOCATION/adme.war
elif [ -s $BULOCATION/adme-1.0.64.war ];then cp $BULOCATION/adme-1.0.64.war $BULOCATION/adme.war
else
	echo -e "\n$RED_FG ERROR:$DEF Web-UI file adme-1.0.64.war or higher not found in $BULOCATION folder, download and place it in the named folder and restart GUI service"
	exit 1
fi
echo -e "\n$GREEN_FG UPGRADE-Step-12:$DEF Refreshing permissions ..."
chmod 760 -R $BULOCATION; chown root:root -R $BULOCATION
chmod 644 -R $BULOCATION/audit/* 2>/dev/null; chown root:root -R $BULOCATION/audit/* 2>/dev/null
chmod 664 -R $BULOCATION/backups/* 2>/dev/null; chown admin:admin -R $BULOCATION/backups/* 2>/dev/null
chmod 664 -R $BULOCATION/grabs/* 2>/dev/null; chown admin:admin -R $BULOCATION/grabs/* 2>/dev/null
chmod 700 $BULOCATION/adme.war; chown root:root $BULOCATION/adme.war
chmod 500 /usr/local/avamar/bin/adme; chown root:root /usr/local/avamar/bin/adme 
chmod 500 /usr/local/avamar/bin/nwutil; chown root:root /usr/local/avamar/bin/nwutil 
chmod 500 /usr/local/avamar/bin/atopnpc; chown root:root /usr/local/avamar/bin/atopnpc 

echo -e "\n$GREEN_FG UPGRADE-Step-13:$DEF Restarting ADMe Web-UI service ..."
# if [ "$activemove" -eq "1" ]
# then
# 	echo -e "\n"
# 	echo -e "$RED_BG$WHITE_FG WARNING:$RED_FG$DEF$RED_FG The Web-UI service has not been started, login as $WHITE_FG[root]$RED_FG then run command:$WHITE_FG [ adme -gui restart ]$DEF"
# 	exit 0
#else
# 	echo -e "$RED_BG$WHITE_FG WARNING:$RED_FG$DEF$RED_FG The Web-UI service has not been started, login as $WHITE_FG[root]$RED_FG then run command:$WHITE_FG [ adme -gui restart ]$DEF"
  	/usr/local/avamar/bin/adme -gui restart
	exit 0
#fi
