#!/bin/bash
RESULT=0

function log() {
	echo "`date` $1"
}
function log_indented() {
	log "===>> $1"
}

function margin() {
	log ""
}

function margin_large() {
	margin
	margin
}

function stop_processes() {
	processes=($@)
	for process in "${processes[@]}"
	do
		log_indented "Stopping ${process} ..."
		sudo service $process stop 
	done
}

function check_file() {
	if [ -f "$2" ]; then
		log_indented "Verifying $1 file $2. File exists."
	else
		log_indented "Failure. $1 file $2 does not exist. Exiting"
		echo "UPGRADE FAILED" > /tmp/upgradeResult.txt
		exit 1
	fi
}

function backup_and_replace() {
	local name=$1
	local replace_with=$2
	local file=/etc/apt/$name
	local file_backup=/var/tmp/$name.orig
	local dir=/etc/apt/$name.d
	local dir_backup=/var/tmp/$name.d.orig

	margin_large
	log_indented "Adapting $file file ..."
	if [ -f $file ]; then
		#Only backup if no backup existing yet (script could be restarted)
		if [ -f $file_backup ]; then
			log "Backup of $file already exists. Probably update script has been restarted."
		else
			log "Creating backup of $file file"
			sudo mv --force $file $file_backup
		fi
	else
		log "Warning. No original file $file found!"
	fi

	if [ ! -d $dir ]; then
		log "Warning. No original folder $dir found! Creating one (empty folder) ..."
		sudo mkdir $dir
	fi

	if [ -d $dir_backup ]; then
		log "Backup of $dir_backup already exists. Probably update script has been restarted."
	else
		log "Creating backup of $dir folder"
		sudo mkdir $dir_backup
		#If not empty (incl. hidden files), move content to target folder
		if [ -n "$(ls -A $dir)" ]; then
			sudo mv --force $dir/* $dir_backup
		else
		log "Original $dir folder seems empty"
		fi
	fi

	log "Activating given $name file"
	sudo mv --force "$replace_with" $file
}

restore() {
	local name=$1
	local file=/etc/apt/$name
	local file_backup=/var/tmp/$name.orig
	local dir=/etc/apt/$name.d
	local dir_backup=/var/tmp/$name.d.orig

	margin_large
	log_indented "Restoring original $file ..."
	log ""
	if [ -f $file_backup ]; then
		sudo mv --force $file_backup $file
	fi
	if [ -d $dir_backup ]; then
		sudo rm -rf $dir
		sudo mv --force $dir_backup $dir
	fi
}

if [ "$#" -lt 1 ]; then
	echo "Please try again with legal command line arguments. Usage:"
	echo "upgradeDevice.sh <sources list file> [<apt config file>] "
	echo "UPGRADE FAILED" > /tmp/upgradeResult.txt
	exit 1
fi

log "Starting NRC/NCN Upgrade Session"
margin_large

#Check if the source list file exists and use it
SOURCES_LIST_FILE=$1
check_file "source list" "$SOURCES_LIST_FILE"
backup_and_replace "sources.list" "$SOURCES_LIST_FILE"
sudo rm -rf /var/lib/apt/lists/*

#If apt config file is provided, verify and use it
if [ "$#" -gt 1 ]; then
  APT_CONFIG_FILE=$2
	check_file "apt config" "$APT_CONFIG_FILE"
	backup_and_replace "apt.conf" "$APT_CONFIG_FILE"
else
	log_indented "No apt configuration file provided"
fi

#Stop the Cinergy processes before starting the upgrade
log_indented "Stopping Cinergy processes:"
stop_processes "barco-cinergy-iccontrolsysteminterface barco-cinergy-icdeviceserver barco-cinergy-iconnectserver"

#Correct any possible failed previous installs
margin_large
log_indented "Correcting any possible failed previous installs ..."
sudo dpkg --configure -a
if [ "$?" != "0" ]; then
	log_indented "Failure. Could not correct previous installs. ABOUT TO FORCEFULLY REMOVE NGINX-FULL AND RETRY !!!"
	sudo DEBIAN_FRONTEND=noninteractive apt-get remove --yes --purge nginx-full
	sudo dpkg --configure -a
fi


#Update the apt-cache
margin_large
log_indented "Synchronizing package index files from the repository ..."
log ""
sudo apt-get update
if [ "$?" != "0" ]; then
	log_indented "Failure. Could not synchronize package index files from the repository. Exiting"
	echo "UPGRADE FAILED" > /tmp/upgradeResult.txt
	exit 1
fi

#Dist-upgrade from the repository
margin_large
log_indented "Performing dist-upgrade ..."
log ""
sudo DEBIAN_FRONTEND=noninteractive apt-get --yes --allow-downgrades --allow-remove-essential --allow-change-held-packages --allow-unauthenticated dist-upgrade  -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" -o Dpkg::Options::="--force-overwrite" -fuy
if [ "$?" != "0" ]; then
	log_indented "Failure. Could not perform dist-upgrade. Exiting"
	RESULT=1
fi

#Restore the original sources list file
restore "sources.list"

#Restore the original apt config files
restore "apt.conf"

#Copy version file and reboot the system if the upgrade was successful
if [ $RESULT = 0 ]; then
	margin_large
	log_indented "Successfully upgraded system. Triggering system reboot"
	echo "UPGRADE SUCCEEDED" > /tmp/upgradeResult.txt
	sudo cp -f /etc/nrc_version /etc/nrc_version_copy
	sudo chown barco /etc/nrc_version_copy
	sudo chmod 0666 /etc/nrc_version_copy
	sudo mv /etc/nrc_version_copy /etc/edu_proxy/config/version
	sudo rm -f /var/log/edu_proxy/deviceCleanup.log
	sudo reboot
else
	echo "UPGRADE FAILED" > /tmp/upgradeResult.txt
fi

exit $RESULT
