###############################################################################
#
# Open iT Mould script accessing the patch change log
#
# Requires the global variable 'backuplog' to contain the path to the backup
# log file
#
# Functions:
#    loadChangelog       : Load the change log into memory
#


# Global variables
map changelog



# Purpose: Load the change log
#          Loads the log into the global variable 'changelog'
# Return value: true if success, false if error (no changelog is not an error)
function loadChangelog

	# Name of change log
	string fname
	eval ( fname = patchesdir . "/change.log" )

	# Reset change log just in case we loaded it before
	mapclear changelog

	# It is OK for the file to not exist
	if ( ! &fexists fname )
		return true
	end

	# Load it
	filetomap fname "\t" changelog
	if ( ! success )
		call "error" ( "Failed to load the change log file \"" . fname . "\"" )
		return false
	end

	# Success
	return true

end


# Purpose: Save the change log (after modifying it)
# Return value: true if success, false if error
function saveChangelog

	# Name of change log
	string fname fnametmp
	eval ( fname = patchesdir . "/change.log" )
	eval ( fnametmp = fname . ".tmp" )

	# Save it
	maptofile changelog "\t" fnametmp
	if ( ! success )
		call "error" ( "Failed to save change log file \"" . fnametmp . "\"" )
		return false
	end

	# Finalize it
	move fnametmp fname
	if ( ! success )
		call "error" ( "Failed to finalize change log file \"" . fnametmp . "\" to \"" . fname . "\"" )
		return false
	end

	# Success
	return true

end


# Purpose: Add link between file and patch in the change log
#          NOTE: You must have called loadChangelog at some point prior to
#          calling this function, and you must call saveChangelog sometime
#          after.
function logChange fname

	# Process path
	strreplace fname "\\" "/"
	strreplace fname "//" "/"

	# Just set the current patch id for the file name
	mapset changelog fname patchid

end


# Purpose: Verify if the given file has been patched by a newer patch
#          NOTE: You must have called loadChangelog at some point prior to
#          calling this function.
# Return value: true if yes, false if not installed, or installed by the
#               current patch or older
function checkPatchFile fname

	# Process path
	strreplace fname "\\" "/"
	strreplace fname "//" "/"

	# Find entry in map
	string foundid
	mapget changelog fname foundid
	if ( ! success )

		# The file has never been patched
		return false

	end

	# Check patch id
	if ( foundid <= patchid )
		return false
	end

	# The file has been patched by a newer patch
	return true

end
