#!/bin/bash
touch /tmp/installer.lock
# creating log location
installerlog='/var/log/sut/sut_installer.log';
mkdir -p /var/log/sut && touch $installerlog;
temp1=$1

echo "input is $1"  >> $installerlog;

if [ -f /opt/sut/bin/sut ]; then
	/opt/sut/bin/sut /waitforupgrade >> $installerlog  2>&1 ;
fi

if ! [ -f /bin/kill -o -f /opt/sut/bin/kill ]; then
	echo "error: Failed dependencies: sut requires kill"  >> $installerlog 2>&1 ;
fi

if ! [ -f /sbin/shutdown -o -f /usr/sbin/shutdown ]; then
	echo "error: Failed dependencies: sut requires shutdown"  >> $installerlog 2>&1 ;
fi

shopt -u nocasematch

if [ "$temp1" = "upgrade" ]; then
	
	#Exporting configuration in case of upgrade or downgrade
	echo $(date) "Exporting SUT configuration" >> $installerlog
	
	if [ -f /opt/sut/bin/sut ];
	then
		exportret=`/opt/sut/bin/sut -installer -exportconfig /usr/local/sut/sut_cfg_bkp.dat >> $installerlog 2>&1` ;
		versionStr=`/opt/sut/bin/sut -installer -version | tr -d '\n' | awk '{print $13}'`
	fi
	
	echo $versionStr >> /var/tmp/sut/sutversion.txt
	echo $(date) "Export command status: " $exportret >> $installerlog ;
	
	

	#Stop the running service if the service is running
	
	if [ -f /opt/sut/bin/sut ]; 
	then
		pidof /opt/sut/bin/sut
	fi
  
	if [ $? == 0 ]; then
		if [ -f /opt/sut/bin/sut ]; 
		then
			/opt/sut/bin/sut -installer -stop >> $installerlog 2>&1
		fi
	fi
else
	# If old backup config file exists in case of fresh installation, removing it as import happens as part of deployfinish for both upgrade and fresh installation based on existance of this file
	if [ -f /usr/local/sut/sut_cfg_bkp.dat ];
	then
		rm -f /usr/local/sut/sut_cfg_bkp.dat >> /var/log/sut/sut_installer.log  2>&1
		if [ $? == 0 ]
		then
			echo $(date) "Old backup config file is removed successfully" >> /var/log/sut/sut_installer.log
		else
			echo $(date) "Failed to remove old backup config file" >> /var/log/sut/sut_installer.log
		fi
	fi
fi
rm -rf /tmp/installer.lock
