# Copyright for URLibService (c) 1995 - 2020,
# by Gerald Banon. All rights reserved.
# Create the main window

package provide dpi.inpe.br/banon/1998/08.02.08.56 2.1

# ----------------------------------------------------------------------
# CreateMainWindow
# used in main and OpenWindow (StartServer.tcl)

proc CreateMainWindow {} {
# runs with start
	global w
	global wdd wir wob wsp clo exi
	global argv
	global environmentArray
	global col
#	global apacheRepository
	global sp.prePostMenu
	global dd.dirPostMenu
	global dd.repPostMenu
	global dd.dirPostponeReduceEntry
	global dd.repPostponeReduceEntry
	global log
#	global posted

# >

# Set options for UNIX
option add *background #c0c0c0	;# systemButtonFace
option add *foreground black
option add *Menu.activeBackground #000080	;# systemActiveCaption
option add *Menu.activeForeground #ffffff	;# systemCaptionText
option add *selectColor #ffffff
option add *selectBackground #000080	;# systemHighligth
option add *troughColor #c0c0c0	;# systemScrollbar
option add *disabledForeground #808080	;# systemDisabledText
# Set options for UNIX - end

# Set window

set w .window
toplevel $w
pack propagate $w false
wm grid $w 1 1 1 1

#puts [$w config]
#set rgb [winfo rgb $w systemButtonFace]
#puts [format "#%03x%03x%03x" \
[expr round([lindex $rgb 0])] \
[expr round([lindex $rgb 1])] \
[expr round([lindex $rgb 2])]]

wm title $w "URLibService"
# set backgroundColor [lindex [$w configure -background] 3]
# puts $backgroundColor
# => SystemButtonFace

# Create a frame for the menu bar.

frame $w.menubar
frame $w.sp -height .47c -relief raised -borderwidth 1

pack $w.menubar -side top -fill x
# pack $w.sp -side top -fill x -expand true
pack $w.sp -side top -fill x

# Create the command buttons.

# set width .7	;# inch
set width .63	;# inch
# set width .525	;# inch
# set height .9	;# cm
set height .81	;# cm
# set height .675	;# cm

# Exit button
frame $w.menubar.exit -width [format "%si" $width] \
	-height [format "%sc" $height]
pack propagate $w.menubar.exit false
pack $w.menubar.exit -side right
set exi [button $w.menubar.exit.1 -command Run-exit -borderwidth 2 -cursor hand2]
#set exi [button $w.menubar.exit.1 -borderwidth 2 -cursor hand2]
ConfigText $exi Exit
pack $exi -fill both -expand true
#bind $exi <Button-1> "Run-exit; continue"	;# continue is to let the double click working
#bind $exi <Double-1> "Run-exit"

# Close button
frame $w.menubar.close -width [format "%si" $width] \
	-height [format "%sc" $height]
pack propagate $w.menubar.close false
pack $w.menubar.close -side right
set clo [button $w.menubar.close.1 -command Run-close -borderwidth 2 -cursor hand2]
#set clo [button $w.menubar.close.1 -borderwidth 2 -cursor hand2]
ConfigText $clo Close
pack $clo -fill both -expand true
#bind $clo <Button-1> "Run-close; continue"	;# continue is to let the double click working
#bind $clo <Double-1> "Run-exit"

# DD button
frame $w.menubar.dd -width [format "%si" $width] \
	-height [format "%sc" $height]
pack propagate $w.menubar.dd false
set wdd [button $w.menubar.dd.1 -command Run-dd -borderwidth 2 \
	-cursor hand2]
ConfigText $wdd DD
pack $wdd -fill both -expand true

# IR button
frame $w.menubar.ir -width [format "%si" $width] \
	-height [format "%sc" $height]
pack propagate $w.menubar.ir false
set wir [button $w.menubar.ir.1 -command Run-ir -borderwidth 2 \
	-cursor hand2]
ConfigText $wir IR
pack $wir -fill both -expand true

# OB button
frame $w.menubar.ob -width [format "%si" $width] \
	-height [format "%sc" $height]
pack propagate $w.menubar.ob false
set wob [button $w.menubar.ob.1 -command Run-ob -borderwidth 2 \
	-cursor hand2 -bg #a0a0e0]
ConfigText $wob OB
pack $wob -fill both -expand true

# SP button
frame $w.menubar.sp -width [format "%si" $width] \
	-height [format "%sc" $height]
pack propagate $w.menubar.sp false
set wsp [button $w.menubar.sp.1 -command Run-sp -borderwidth 2 \
	-cursor hand2]
ConfigText $wsp SP
pack $wsp -fill both -expand true

$wdd config -state disabled
$wir config -state disabled
$wob config -state disabled
$wsp config -state disabled

# pack $w.menubar.dd $w.menubar.ob $w.menubar.sp -side left
pack $w.menubar.dd $w.menubar.ir $w.menubar.ob $w.menubar.sp -side left

# CreateMain $posted
CreateMain 0

# Display message
# DD dialog
label $w.sp.dd -bg #ffffcc \
	-relief solid -borderwidth 1
ConfigText $w.sp.dd " Depositing a Document "
bind $w.menubar.dd <Enter> \
	"DisplayMessage $w.sp.dd $w.sp nw 0 0 [format "%si" [expr 0 * $width]]"
bind $w.menubar.dd <Leave> "DeleteMessage"
bind $wdd <Button> "DeleteMessage"

# IR dialog
label $w.sp.ir -bg #ffffcc \
	-relief solid -borderwidth 1
# ConfigText $w.sp.ir " Installing a Repository "
bind $w.menubar.ir <Enter> \
	"DisplayMessage $w.sp.ir $w.sp nw 0 0 [format "%si" [expr 1 * $width]]"
bind $w.menubar.ir <Leave> "DeleteMessage"
bind $wir <Button> "DeleteMessage"

# OB dialog
label $w.sp.ob -bg #ffffcc \
	-relief solid -borderwidth 1
ConfigText $w.sp.ob " Open your Browser "
bind $w.menubar.ob <Enter> \
	"DisplayMessage $w.sp.ob $w.sp nw 0 0 [format "%si" [expr 2 * $width]]"
bind $w.menubar.ob <Leave> "DeleteMessage"
bind $wob <Button> "DeleteMessage"

# SP dialog
label $w.sp.sp -bg #ffffcc \
	-relief solid -borderwidth 1
ConfigText $w.sp.sp " Setting the Preferences "
bind $w.menubar.sp <Enter> \
	"DisplayMessage $w.sp.sp $w.sp nw 0 0 [format "%si" [expr 3 * $width]]"
bind $w.menubar.sp <Leave> "DeleteMessage"
bind $wsp <Button> "DeleteMessage"

# Close dialog
label $w.sp.cl -bg #ffffcc \
	-relief solid -borderwidth 1
ConfigText $w.sp.cl " Close this Window and Leave the Servers On "
bind $w.menubar.close <Enter> \
	"DisplayMessage $w.sp.cl $w.sp ne 1 0 [format "%si" [expr - $width]]"
bind $w.menubar.close <Leave> "DeleteMessage"
bind $clo <Button> "DeleteMessage"

# Exit dialog
label $w.sp.ex -bg #ffffcc \
	-relief solid -borderwidth 1
ConfigText $w.sp.ex " Exit from URLibService (turns off the servers) "
bind $w.menubar.exit <Enter> \
	"DisplayMessage $w.sp.ex $w.sp ne 1 0 [format "%si" 0]"
bind $w.menubar.exit <Leave> "DeleteMessage"
bind $exi <Button> "DeleteMessage"
# Display message - end

bind .window <Destroy> NukedWindow

set sp.prePostMenu 0	;# 0 don't post; 1 post
set dd.dirPostMenu 0	;# 0 don't post; 1 post
set dd.repPostMenu 0	;# 0 don't post; 1 post
# we need to postpone ReduceEntry untill the UpdateMenu is
# completed in order to have activated menu entries
# (case of repeated clicks on <)
set dd.dirPostponeReduceEntry 1 ;# 0 don't postpone; 1 postpone	
set dd.repPostponeReduceEntry 1 ;# 0 don't postpone; 1 postpone

# Start the SPDialog
if ![info exists environmentArray(localCollectionIndexRepository)] {
	tkwait visibility $w
	Run-sp
}
# Start the SPDialog - end

# <
}

# CreateMainWindow - end
# ----------------------------------------------------------------------
# DisableButtons

proc DisableButtons {{list {wdd wir wsp}}} {
# runs with start
	global wdd wir wob wsp clo exi
# puts [CallTrace]

	foreach widget $list {
		[subst $$widget] config -state disabled
	}
}

# DisableButtons - end
# ----------------------------------------------------------------------
# EnableButtons

proc EnableButtons {{list {wdd wir wob wsp clo exi}}} {
# runs with start
	global wdd wir wob wsp clo exi
	global environmentArray
	global homePath
	global loCoInRep
	global w
# puts [CallTrace]

	foreach widget $list {
		if {[info exists environmentArray(registrationFlag)] && !$environmentArray(registrationFlag) && [string equal {wdd} $widget]} {continue}	;# environmentArray(registrationFlag) doesn't exist at installation time
		if [string equal {wir} $widget] {
			if {[info exists loCoInRep] && ![file exists $homePath/col/$loCoInRep/auxdoc/xxx]} {
				ConfigText $w.sp.ir " Installing a Repository - administrator unregistered "
				continue	;# the administrator must be registered
			} else {
				ConfigText $w.sp.ir " Installing a Repository "
			}
		}
		[subst $$widget] config -state normal
	}
}

# EnableButtons - end
# ----------------------------------------------------------------------
# Run-dd

proc Run-dd {} {
# runs with start
	global w
	DisableButtons
#	grid forget $w.main.output.log
#	grid forget $w.main.output.yscroll
#	pack forget $w.main
	CloseMain
	destroy $w.main
	destroy .xxrepository
	destroy .bchelp
	DDDialog
}

# Run-dd - end
# ----------------------------------------------------------------------
# Run-ir

proc Run-ir {} {
# runs with start
	global keyRepositoryList
	global log
	global environmentArray
	global homePath
	global loCoInRep

	DisableButtons
	
# Waiting for the completion of other repository insertions
	WaitQueue
# Waiting for the completion of other repository insertions - end

	set command [InstallRepository 1]	;# set repositoryList
	if [regexp {installing} $command] {
# execute Dialog
		if [eval $command] {
# Dialog returned 1
			LeaveQueue
			EnableButtons
			return
		}
# yes install
		set buttonCursorState [SetWaitingState .window.main.bc.rep.h2.entry.entry bc]
# Compute the log
		LogInsert [list [list Insert $log end {new line}]] 1 0	;# blk line
		LogInsert [list [list Insert $log end \
			{installing repository <$var1> ...} \
			{} $packedRepository] \
			[list TagAdd $log fixed9 \
			{<$var1>} -forward $packedRepository]] 0 0
		LogInsert [list [list Insert $log insert {new line}]] 0 1
# Compute the log - end
		DisplayTextLog
# administratorCodedPassword
		Load $homePath/col/$loCoInRep/auxdoc/xxx data binary
		set data [UnShift $data]
		set administratorCodedPassword [lindex $data end]
#		set command [Eval InstallRepository 0 0]
		set command [Eval InstallRepository 0 0 1 0 0 {} $administratorCodedPassword]	;# Apache need to be restarted when the repository contains a CGI script
		if [regexp {cannot delete the old doc} $command] {
			eval $command
			UnsetWaitingState .window.main.bc.rep.h2.entry.entry bc $buttonCursorState
			ControlBCButtonState .window.main.bc.rep.h2.entry.entry bcRepository bc(result1)
			LeaveQueue
			EnableButtons
			return
		} elseif {![string equal {} $command]} {
			puts $command
			UnsetWaitingState .window.main.bc.rep.h2.entry.entry bc $buttonCursorState
			ControlBCButtonState .window.main.bc.rep.h2.entry.entry bcRepository bc(result1)
			LeaveQueue
			EnableButtons
			return
		}
#		source ../auxdoc/.environmentArray.tcl	;# environmentArray might have been changed in post and must be reloaded with start
		SourceWithBackup ../auxdoc/.environmentArray.tcl environmentArray	;# environmentArray might have been changed in post and must be reloaded with start - added by GJFB in 2010-08-05
		LoadTextLog
		DisplayTextLog
# installation completed
# Update keyRepositoryList
#		set storeKeyRepositoryListFlag 0
		foreach rep $repositoryList {
#			set storeKeyRepositoryListFlag [UpdateKeyRepositoryList $rep $storeKeyRepositoryListFlag]
			UpdateKeyRepositoryList $rep
		}
#		if $storeKeyRepositoryListFlag {
#			StoreList keyRepositoryList ../auxdoc/.keyRepositoryList.tcl
#		}
# Update keyRepositoryList - end
		SetIndicator bc .window.main.bc.rep.h2.entry.entry
		InternalLink .window.main.bc.rep.h2.entry.entry bcRepository \
			bc(result1) $packedRepository
		UnsetWaitingState .window.main.bc.rep.h2.entry.entry bc $buttonCursorState
		ControlBCButtonState .window.main.bc.rep.h2.entry.entry bcRepository bc(result1)
	} else {
		eval $command
	}
	LeaveQueue
	EnableButtons
}

# Run-ir - end
# ----------------------------------------------------------------------
# InstallRepository
# test value is 0 or 1, 1 means just to test, 0 means just to install (without testing)
# logFlag value is 0 or 1, 1 means to write in the log, 0 means means to don't write
# startApacheServer2 values are 0 or 1, 1 means to restart Apache, 0 means to don't restart
# copyDocZip value is 0 or 1,
# 1 means to copy doc.zip in the download directory of the repository,
# 0 means to delete the doc.zip in the download directory of the repository
# forceRegistration value is 0 or 1
# 1 means to force registration
# (set to 1 in captureRepository and used in RegisterRepository)
# expectedRepository is the repository name of the repository to be installed
# if expectedRepository is not empty then it must match the name of the packed repository
# otherwise nothing is installed
# called only by ImportRepository (utilitiesStart.tcl) and Run-ir
# returns a Dialog command line or empty when the installation is made


proc InstallRepository {
	{test 0} {logFlag 1} {startApacheServer2 1}
	{copyDocZip 1} {forceRegistration 0} {expectedRepository {}} {administratorCodedPassword {}}
} {
# runs with post
# runs with start (with test == 1)
	global homePath
	global pwd
	global col
	global unZipPath
	global unZipRepository
	global zipPath
	global URLibServiceRepository
	global log
	global loCoInRep
	global startApacheServer
	global environmentArray
	global tcl_platform
	
	upvar repositoryList repositoryList	;# used by Run-ir
	upvar packedRepository packedRepository	;# used by Run-ir
	
	if !$test {
		set message [CheckAdministratorPassword administrator $administratorCodedPassword]
		if ![string equal {} $message] {return $message}	;# unfair call - do nothing
	}

	if [file exists $homePath/doc.zip] {
# doc.zip exists
		file delete $homePath/col/$URLibServiceRepository/auxdoc/packedRepository
# auxdoc/packedRepository
# auxdoc/repositoryList
		if [string equal {} $unZipPath] {
			return [list Dialog OK disabled -1 IR {unzip is missing} $homePath]
		}
		if [catch {exec $unZipPath -o\
		$homePath/doc.zip packedRepository repositoryList -d \
		$homePath/col/$URLibServiceRepository/auxdoc} error] {
# puts $error
			if [regexp {packedRepository} $error] {
# not a repository
# caution: filename not matched:  packedRepository
				return [list Dialog OK disabled -1 IR {not a repository} $homePath]
			} else {
# not a zipfile
# End-of-central-directory signature not found
				return [list Dialog OK disabled -1 IR {not a zipfile} $homePath]
			}
		}
		Load $homePath/col/$URLibServiceRepository/auxdoc/packedRepository packedRepository
		if {![string equal {} $expectedRepository] && ![string equal $packedRepository $expectedRepository]} {
			return {unexpected repository}
		}

		if [string equal {} $packedRepository] {
# not a repository
			return [list Dialog OK disabled -1 IR {not a repository} $homePath]
		} else {
# a repository
			Load $homePath/col/$URLibServiceRepository/auxdoc/repositoryList repositoryList
			if {[lsearch $repositoryList $URLibServiceRepository] != -1} {
				return [list Dialog OK disabled -1 IR {doc.zip contains URLibService} $homePath $packedRepository]
			}
			if [file isdirectory $homePath/col/$packedRepository] {
# the repository exists
				if [GetDocumentState $packedRepository] {
# the repository in the collection contains an original document
					return [list Dialog OK disabled -1 IR {there is an original document} $packedRepository]
				} else {
# the repository in the collection doesn't contain an original document
					if $test {
						return [list Dialog {Yes No} {disabled active} {0 0} IR {installing an existing repository} $packedRepository]
					}
				}
			} else {
# the repository doesn't exist
				if $test {
					return [list Dialog {Yes No} {disabled active} {0 0} IR {installing a new repository} $packedRepository]

				}
			}
# end of test
# Yes, install
# Compute the log
			if $logFlag {
				LogInsert [list [list Insert $log end {new line}]] 1 0 0	;# blk line
				LogInsert [list [list Insert $log end \
					{installing repository <$var1> ...} \
					{} $packedRepository] \
					[list TagAdd $log fixed9 \
					{<$var1>} -forward $packedRepository]] 0 0 0
				LogInsert [list [list Insert $log insert {new line}]] 0 1 0
			}
# Compute the log - end
# Zip the old doc and service
			set fileList {}
			foreach rep $repositoryList {
				if [file isdirectory $homePath/col/$rep] {
					lappend fileList col/$rep/doc
					lappend fileList col/$rep/service
				}
			}
			if ![string equal {} $fileList] {
				set command "$zipPath -r"
				set option ""
				set type zip
				file mkdir $homePath/col/$URLibServiceRepository/auxdoc/tmpForInstallRepository
				if [file exists $homePath/col/$URLibServiceRepository/auxdoc/tmpForInstallRepository/doc.$type] {
					file delete $homePath/col/$URLibServiceRepository/auxdoc/tmpForInstallRepository/doc.$type
				}
				cd $homePath
				catch {eval "exec $command $option $homePath/col/$URLibServiceRepository/auxdoc/tmpForInstallRepository/doc.$type $fileList"}
				cd $pwd
			}
# Zip the old doc and service - end

# Delete the old doc and service
			foreach rep $repositoryList {
				if [file isdirectory $homePath/col/$rep] {
#	file delete -force $homePath/col/$rep/doc		;# doesn't work with ir dpi.inpe.br/banon/1998/08/02/08.56 (produces a permission denied)
#	file delete -force $homePath/col/$rep/service	;# doesn't work with ir dpi.inpe.br/banon/1998/08/02/08.56 (produces a permission denied)
					if ![string equal $unZipRepository $rep] {
# rep must not contain UnZip (otherwise UnZip cannot work later on)
						set dir $homePath/col/$rep/doc
#						set fileList [glob -nocomplain $dir/.* $dir/*]
#						set fileList [lrange $fileList 2 end]	;# drop . ..
						set fileList [glob -nocomplain -- $dir/* $dir/.?*]
						set index [lsearch -exact $fileList $dir/..]
						set fileList [lreplace $fileList $index $index]
						set index [lsearch -exact $fileList $dir/tmp]	;# added by GJFB in 2013-02-09 to preserve the doc/tmp direcory - useful for Administrator page for setting field value attributes (iconet.com.br/banon/2007/01.01.16.00)
						set fileList [lreplace $fileList $index $index]	;# exclude doc/tmp from the fileList - added by GJFB in 2013-02-09
						foreach file $fileList {
							if [catch {file delete -force $file} error] {
# cannot delete the old doc
# Restore the deleted files
								exec $unZipPath -n $homePath/col/$URLibServiceRepository/auxdoc/tmpForInstallRepository/doc.zip -d $homePath
# Restore the deleted files - end
								file delete -force $homePath/col/$URLibServiceRepository/auxdoc/tmpForInstallRepository
								return [list Dialog OK disabled -1 IR {cannot delete the old doc} $packedRepository $error]
							}
						}
					}
					set dir $homePath/col/$rep/service
#					set fileList [glob -nocomplain $dir/.* $dir/*]
#					set fileList [lrange $fileList 2 end]	;# drop . ..
					set fileList [glob -nocomplain -- $dir/* $dir/.?*]
					set index [lsearch -exact $fileList $dir/..]
					set fileList [lreplace $fileList $index $index]
					set index [lsearch -exact $fileList $dir/authenticatedUsers]	;# added by GJFB in 2017-05-08 to preserve the service/authenticatedUsers direcory - each collection has is own authenticatedUsers
					set fileList [lreplace $fileList $index $index]	;# exclude service/authenticatedUsers from the fileList - added by GJFB in 2017-05-08
					foreach file $fileList {
						file delete -force $file
					}
				}
			}
# Delete the old doc and service - end

# Unzip each repository which doesn't contain an original document
			foreach rep $repositoryList {
# set xxx $rep
# Store xxx C:/tmp/bbb auto 0 a
				if {![file isdirectory $homePath/col/$rep] || ![GetDocumentState $rep]} {
# the repository doesn't exist or doesn't contain an original document
# UNZIP
# unzip 6.0 in urlib.net/www/2010/12.28.21.51 doesn´t restore the original timestamp of files whose file type is .eml
# this bug creates a false modified document state when exporting a repository containing files with such file type
# (observed by GJFB in 2014-05-24)
					if [catch {exec $unZipPath -o \
					$homePath/doc.zip col/$rep/* -d $homePath} error] {
# Restore
						if ![string equal $unZipRepository $packedRepository] {
# packedRepository must not contain UnZip (UnZip of UnZip above doesn't work and produces an error)
							catch {exec $unZipPath -o \
							$homePath/col/$URLibServiceRepository/auxdoc/tmpForInstallRepository/doc.zip -d $homePath}
						}
# Restore - end
# set xxx $error
# Store xxx C:/tmp/bbb auto 0 a
						puts $error
					} else {
# unzip done
						file delete $homePath/col/$rep/download/doc.zip	;# added by GJFB in 2020-04-22 - in this way the doc.zip will be updated (recreated) when needed (see MakeDownloadFile)
						if {$tcl_platform(platform) == "unix"} {
							foreach {userName groupName} [lrange [exec ls -l | grep post$] 2 3] {break}
							if [string equal {root} $userName] {
								if [file owned post] {
# user is root
#									exec chgrp -R $groupName $homePath/col/$rep/doc	;# otherwise tcl pages might not work when using port 80 - doesn't work when installing an original document because later on remote updating need to change, for example, service/visibility (in this case group must be changed from root to groupName) - commented by GJFB in 2010-12-02
									exec chgrp -R $groupName $homePath/col/$rep	;# otherwise tcl pages might not work when using port 80 - changing group (from root to groupName) in the service directory is important when remotely updating a document (with Submit), otherwise, for example, service/visibility cannot be updated  - added by GJFB in 2010-12-02
									exec chmod -R g+w $homePath/col/$rep	;# otherwise tcl pages might not work when using port 80 - the files must have a write persmission for the group in order to allow updating by urlibadm (otherwise, a redirection problem might occur when exporting a Submission Form repository)
								}
							}
						}
					}
				}
# set xxx 2
# Store xxx C:/tmp/bbb auto 0 a
			}
			file delete -force $homePath/col/$URLibServiceRepository/auxdoc/tmpForInstallRepository
# Unzip each repository which doesn't contain an original document - end

# Update environmentArray(mirrorRepList)
# useful when importing a bibliographic mirror
# requires resarting the URLibService because of Apache
			set flag 0
			foreach rep $repositoryList {
				if [TestContentType $rep Mirror] {
					if {[lsearch -exact $environmentArray(mirrorRepList) $rep] == -1} {
						lappend environmentArray(mirrorRepList) $rep
						set flag 1
					}
				}
			}
			if $flag {
				set environmentArray(mirrorRepList) [lsort -unique $environmentArray(mirrorRepList)]
# SAVE
#				StoreArray environmentArray ../auxdoc/.environmentArray.tcl
#				StoreArray environmentArray ../auxdoc/.environmentArray2.tcl	;# backup
#				StoreArrayWithBackup environmentArray ../auxdoc/.environmentArray.tcl	;# added by GJFB in 2010-08-05
				StoreArrayWithBackup environmentArray ../auxdoc/.environmentArray.tcl w list	;# added by GJFB in 2010-08-05
			}
# Update environmentArray(mirrorRepList) - end

# download completed
# Update the collection
			UpdateCollection $repositoryList 1	;# UpdateRepositoryProperties is done here
# Update the collection - end
# Add the auxdoc and source directories, and create the download files
			foreach rep $repositoryList {
				file mkdir $homePath/col/$rep/auxdoc
				file mkdir $homePath/col/$rep/source
# Create the download file
				if [string equal $rep $packedRepository] {
					file mkdir $homePath/col/$rep/download
					if $copyDocZip {
						file copy -force $homePath/doc.zip $homePath/col/$rep/download/doc.zip
					} else {
						file delete $homePath/col/$rep/download/doc.zip
					}
#				} else {
#					UpdateDownloadFile $rep	;# may set saveMetadata to 1
				}
# Create the download file - end
#				if $startApacheServer2 {UpdateAccessFile $rep}	;# commented by GJFB in 2018-09-08
				UpdateAccessFile $rep	;# added by GJFB in 2018-09-08 - since 2013-12-02 ImportRepository in Administrator Page didn't restart Apache
			}
# Add the auxdoc and source directories, and create the download files - end

# Start apache server
			set flag 0
			foreach rep $repositoryList {
#				if [TestContentType $rep {CGI Script}] #	;# commented by GJFB in 2024-05-09
				if {0 || [TestContentType $rep {CGI Script}] || [TestContentType $rep {Mirror}]} {	;# added by GJFB in 2024-05-09 - installing Mirror also requires restarting Apache - similar code in col/dpi.inpe.br/banon-pc@1905/2005/02.19.00.40/cgi/script.tcl
					set flag 1
					break
				}
			}
			if $flag {
#				set startApacheServer 1
				set startApacheServer $startApacheServer2
				StartApacheServer
			}
# Start apache server - end
		}
	} else {
# doc.zip doesn't exist
		return [list Dialog OK disabled -1 IR {no doc.zip} $homePath]
	}

# Register repository name
#	RegisterRepository $packedRepository $forceRegistration	;# RegisterRepositoryName need to be updated to include registration of copies (now a copy has an empty host collection value)
# Register repository name - end

# Compute the log
	LogInsert [list [list Insert $log end {new line}]] 1 0	;# blk line
	LogInsert [list [list Insert $log end \
		{repository <$var1> installed} \
		{} $packedRepository] \
		[list TagAdd $log fixed9 \
		{<$var1>} -forward $packedRepository]] 0 0
	LogInsert [list [list Insert $log insert {new line}]] 0 1
# Compute the log - end
}

# InstallRepository - end
# ----------------------------------------------------------------------
# Run-ob

proc Run-ob {} {
# runs with start
	global loBiMiRep
	global environmentArray
	global webLanguageTable
	set language $environmentArray(spLanguageEntry)
	Link {} [ReturnHTTPHost]/col/$loBiMiRep/doc/mirror.cgi?languagebutton=$webLanguageTable($language)
}

# Run-ob - end
# ----------------------------------------------------------------------
# Run-sp

proc Run-sp {} {
# runs with start
	global w
	DisableButtons {wdd wir wsp clo}
#	grid forget $w.main.output.log
#	grid forget $w.main.output.yscroll
	CloseMain
	destroy $w.main
	destroy .xxrepository
	destroy .bchelp
	SPDialog
}

# Run-sp - end
# ----------------------------------------------------------------------
# Run-close

proc Run-close {} {
# runs with start
	global w
#	global applicationName
	global keyRepositoryList
	global bcChoice1
	global closing
# SAVE
	set closing 1	;# used in NukedWindow
	set bcChoice1 {}
	CloseMain
	if [info exists keyRepositoryList] {
		StoreList keyRepositoryList ../auxdoc/.keyRepositoryList.tcl	;# added by GJFB in 2017-12-27 - mandatory to recover the current keyRepositoryList when returning to the URLibService windows
	}
#	Eval StoreArray referenceTable ../auxdoc/.referenceTable.tcl
#	Eval StoreArray repositoryProperties ../auxdoc/.repositoryProperties.tcl
#	Eval SaveMetadata
#	Unset startApplicationInUse	;# commented by GJFB in 201-12-17
	catch {Unset startApplicationInUse}	;# added by GJFB in 201-12-17 - catch is required when post is down
	if [winfo exist .xxdirectory] {wm withdraw .xxdirectory}
	if [winfo exist .xxrepository] {wm withdraw .xxrepository}
	if {[info exists w] && [winfo exist $w]} {wm withdraw $w}
#	after 1000 {wm withdraw $w}	;# delay is to let the double click work
	exit
# SAVE - end
}

# Run-close - end
# ----------------------------------------------------------------------
# Run-exit

proc Run-exit {} {
# runs with start and post
##	global localURLibServer
	global applicationName
	global keyRepositoryList
	global bcChoice1
##	global tcl_platform
	global loCoInRep
#	global saveMetadata
	global pwd
	global homePath
	global URLibServiceRepository
#	global serverRoot
#	global ibiToArchiveServiceArray
	global tcl_platform
	global unfairAddrList

# Save unfairAddrList
	if {$tcl_platform(platform) == "unix"} {
# unfairAddrList is updated in AcceptCommunication
		if [info exist unfairAddrList] {	
			Store unfairAddrList $homePath/col/$URLibServiceRepository/auxdoc/@unfairAddrList
			puts [StoreLog {notice} {Run-exit} "the unfairAddrList was $unfairAddrList"]	;# added by GJFB in 2021-07-09
		}
	}
# Save unfairAddrList - end

	if {$applicationName == "start"} {
# with start
if 0 {
		cd $serverRoot/conf/VirtualHost2
		set virtualHostConfList [glob -nocomplain *]
		cd $pwd
		if {[llength $virtualHostConfList] > 1} {
			Dialog OK disabled -1 Start {more than one local collection are posted} $virtualHostConfList
			return
		}
}
		set bcChoice1 {}
		CloseMain
		if [info exists keyRepositoryList] {
			StoreList keyRepositoryList ../auxdoc/.keyRepositoryList.tcl
		}
		file delete ../auxdoc/.repositoryListForStart.tcl
		if [info exists loCoInRep] {
# URLibService has already been installed
if 1 {
			if [catch {StopApacheServer} message] {
				puts $message
				return
			}
# httpd.pid file deleted
}
			Load ../auxdoc/pid pid
			if [catch {Eval Run-exit $pid} message] {
				puts $message
				return
			}
		}
		bind .window <Destroy> {}	;# otherwise NukedWindow is called at exit (this would be a problem with SunOs)
# EXIT
		exit
	} else {
# with post
# unpost
		SaveAllData
#		puts {stopping the URLib server...}	;# may produce: error writing "stdout": I/O error (when starting post in unix using putty.exe and without: at now + 1 minute)
		StoreIndex 0
		
		InformURLibSystem 1	;# added by GJFB in 2010-09-20 - inform that the local collection is beeing unposted
	
##		set log "Run-exit:\nstopping URLibService \[[clock format [clock seconds] -format %Y:%m.%d.%H.%M.%S]\]\n"
#		set log "\[[clock format [clock seconds] -format %Y:%m.%d.%H.%M.%S]\] \[notice\] Run-exit:\nstopping URLibService\n"
#		Store log $homePath/@errorLog auto 0 a
		StoreLog {notice} {Run-exit} {stopping URLibService}
	}
#	exit	;# now exit is in ServeLocalCollection
}

# Run-exit - end
# ----------------------------------------------------------------------
# SaveAllData
# used in Run-exit

proc SaveAllData {} {
# run with post
	global saveMetadata
	global ibiToArchiveServiceArray
	global uriToResolverURLArray
	global homePath
	global loCoInRep

	SaveRepositoryProperties 1
	SaveReferenceTable 1
	set saveMetadata 1
	SaveMetadata 1
	if [info exists ibiToArchiveServiceArray] {
		StoreArrayWithBackup ibiToArchiveServiceArray $homePath/col/$loCoInRep/auxdoc/ibiToArchiveServiceArray.tcl w list
	}
	if [info exists uriToResolverURLArray] {
		StoreArrayWithBackup uriToResolverURLArray $homePath/col/$loCoInRep/auxdoc/uriToResolverURLArray.tcl w list
	}
## migration - 2017-11-23
#		file delete $homePath/col/$loCoInRep/auxdoc/ibiToArquiveServiceArray.tcl	;# old file name - not used anymore
#		file delete $homePath/col/$loCoInRep/auxdoc/ibiToArquiveServiceArrayBackup.tcl	;# old file name - not used anymore
## migration - 2017-11-23 - end
		file delete ../auxdoc/.repositoryListForPost.tcl
}
	
# SaveAllData - end
# ----------------------------------------------------------------------
# CreateMain
# Creates a text widget to log the output
# and limits the log size

proc CreateMain {flag} {
# runs with start
	global w
	global log
#	global posted
#	global editorPath	;# commented by GJFB in  2011-03-19
	global loCoInRep
	global homePath
	global commonWords

	global bcRepository
	global bc.repPostMenu
	global typeTable
	global listNameTable
	global bcChoice1
	global bcSearch
	global aBrowse
	global bcSearchResult

	global environmentArray

	frame $w.main

	set bcRepository bcRepository
	set bc.repPostMenu 0
	set typeTable(bcRepository) .rep.
	set listNameTable(bcRepository) keyRepositoryList
	set listNameTable(bcSearch) {}
	SetInitialValue bcReverse 0
	SetInitialValue bcSearch 0
	SetInitialValue bcChoice1 {}	;# used by Selector
	SetInitialValue bcSearchEntry {}
	SetInitialValue bcSelectedKeyRepList {}
#	SetInitialValue bcSearchSelectMenu {}
#	SetInitialValue bcRepositorySelectMenu {}
#	if !$bcSearch {SetInitialValue bcSearchResult {}}
#	SetInitialValue bcSearchResult {}
	if [info exists environmentArray(bcSearchResult)] {
		set bcSearchResult $environmentArray(bcSearchResult)
	}
	frame $w.main.bc
	frame $w.main.bc.rep
	Header $w.main.bc "Browsing the Local Collection"
	frame $w.main.bc.rep.h01
	label $w.main.bc.rep.h01.lb -font {courier 9}
	frame $w.main.bc.rep.h02
	label $w.main.bc.rep.h02.lb -font {courier 9}
	frame $w.main.bc.rep.h1
	label $w.main.bc.rep.h1.lb1 -font {courier 9}
	label $w.main.bc.rep.h1.lb2 -font {courier 9}
	frame $w.main.bc.rep.h2
	set aBrowse [Selector $w.main.bc.rep.h2 bcRepository bc 1 keyRepositoryList]

#	frame $w.main.bc.rep.sp -height .1c	;# extra space

	set width 2.6	;# 4 * 2.6 == 10 + .4 (.4 == extra space between buttons)
	set height .5
	set lb [frame $w.main.bc.rep.label -width 10.4c -height .5c]
	set lb1 [frame $lb.lb1 -width [format "%sc" $width] \
			-height [format "%sc" $height]]
	label $lb1.lb1 -fg #999999
	ConfigText $lb1.lb1 {out-of-date \ndocument}
	set font [lindex [$lb1.lb1 configure -font] end]
# puts [$lb1.lb1 configure -font]
	$lb1.lb1 configure -font {$font 6 roman}
	set lb2 [frame $lb.lb2 -width [format "%sc" $width] \
			-height [format "%sc" $height]]
	label $lb2.lb2 -fg #999999
	ConfigText $lb2.lb2 {not registered \nrepository}
	$lb2.lb2 configure -font {$font 6 roman}
	set lb3 [frame $lb.lb3 -width [format "%sc" $width] \
			-height [format "%sc" $height]]
	label $lb3.lb3 -fg #999999
	ConfigText $lb3.lb3 {not registered \ndocument}
	$lb3.lb3 configure -font {$font 6 roman}
	set lb4 [frame $lb.lb4 -width [format "%sc" $width] \
			-height [format "%sc" $height]]
	label $lb4.lb4 -fg #999999
	ConfigText $lb4.lb4 {not captured \nrepository}
	$lb4.lb4 configure -font {$font 6 roman}
	
	set width 2.2
	set height .6
	set b [frame $w.main.bc.button -width 10c -height .8c]
	set bedit [frame $b.edit -width [format "%sc" $width] \
			-height [format "%sc" $height]]
	set bsp1 [frame $b.sp1 -width .4c] ;# extra space
	set breload [frame $b.reload -width [format "%sc" $width] \
			-height [format "%sc" $height]]
	set bsp2 [frame $b.sp2 -width .4c] ;# extra space
	set bdelete [frame $b.delete -width [format "%sc" $width] \
			-height [format "%sc" $height]]
	set bhelp [frame $b.help -width [format "%sc" $width] \
			-height [format "%sc" $height]]
#	button $bedit.edit \
		-command "EditMetadata $w.main.bc.rep.h2.entry.entry bc(result1) {}" \
		-cursor hand2
	menubutton $bedit.edit \
		-cursor hand2 -relief raised -menu $bedit.edit.menu
	menu $bedit.edit.menu -tearoff 0

#	bind $bedit.edit <1> [list CreateEditMenu $bedit.edit.menu \
		[list EditMetadata $w.main.bc.rep.h2.entry.entry bc(result1)]]	;# button press
	bind $bedit.edit <1> [list CreateEditMenu $bedit.edit.menu \
		[list DisplayEditMetadata $w.main.bc.rep.h2.entry.entry bcRepository \
		bc(result1) #dddddd]]	;# button press

	button $breload.reload \
		-command "PerformCheck $w.main.bc.rep.h2.entry.entry bcRepository bc(result1) 1 0" \
		-cursor hand2
	bind $breload.reload <3> "PerformCheck $w.main.bc.rep.h2.entry.entry bcRepository bc(result1) 1 0 1"
	button $bdelete.delete \
		-command "DeleteRepository $w.main.bc.rep.h2.entry.entry bcRepository bc(result1)" \
		-cursor hand2 -state disabled
	button $bhelp.help \
		-command "DisplayText $w.main.bc bcRepository bc(result1) .bchelp #ffffcc" \
		-cursor hand2
	ConfigText $bedit.edit Edit
	ConfigText $breload.reload Reload
	ConfigText $bdelete.delete Delete
	ConfigText $bhelp.help Help

	pack $w.main.bc.rep.h01.lb
	pack $w.main.bc.rep.h02.lb
	pack $w.main.bc.rep.h1.lb1 -side left
	pack $w.main.bc.rep.h1.lb2 -side right
	pack $w.main.bc.lb -side top
	pack $w.main.bc.rep.h01 -side top -fill both -expand true
	pack $w.main.bc.rep.h02 -side top -fill both -expand true
	pack $w.main.bc.rep.h1 -side top -fill both -expand true
	pack $w.main.bc.rep.h2 -side top -fill both -expand true

#	pack $w.main.bc.rep.sp -side top	;# extra space
	pack $lb -side top
	pack propagate $lb false

	pack propagate $lb1 false
	pack propagate $lb2 false
	pack propagate $lb3 false
	pack propagate $lb4 false
	pack $lb1 -side left
	pack $lb2 -side left
	pack $lb3 -side left
	pack $lb4 -side left
	pack $lb1.lb1 -fill both
	pack $lb2.lb2 -fill both
	pack $lb3.lb3 -fill both
	pack $lb4.lb4 -fill both

	pack $w.main.bc.rep -side top -fill both -expand true

	pack $b -side top -pady .15c
	pack propagate $b false

	pack propagate $bedit false
	pack propagate $breload false
	pack propagate $bdelete false
	pack propagate $bhelp false

	pack $bedit -side left
	pack $bsp1 -side left
	pack $breload -side left
	pack $bsp2 -side left
	pack $bhelp -side left
	pack $bdelete -side right

	pack $bedit.edit -fill both
	pack $breload.reload -fill both
	pack $bhelp.help -fill both
	pack $bdelete.delete -fill both

	pack $w.main.bc -side top -fill x -padx .5c -pady .25c
	if $flag {
		set bcChoice1 repository ;# important to enable button 2.2 in UpdateMenu
		EnableEntry $aBrowse bcRepository bc(result1) keyRepositoryList
		SetIndicator bc $w.main.bc
		if $bcSearch {
			SetBackgroundEntry $aBrowse.entry bcRepository bc(result1)
		}
	}

	SetGeometry
#	frame $w.main.output
#	set log [text $w.main.output.log \
		-borderwidth 2 -relief raised -setgrid true \
		-yscrollcommand "$w.main.output.scroll set" -bg gray85 \
		-cursor double_arrow -wrap word]
	set log [Scrolled_Widget text $w.main.output log \
		-borderwidth 2 -relief raised -setgrid true \
		-bg gray85 \
		-cursor double_arrow -wrap word \
		-padx .2c -pady .2c]
#	scrollbar $w.main.output.scroll -command "$w.main.output.log yview"
	TextStyles $log
#	pack $w.main.output.scroll -side right -fill y
#	pack $w.main.output.log -side left -fill both -expand true
	pack $w.main.output -side top -fill both -expand true
	pack $w.main -fill both -expand true
	bind $w <1> "ProcessButton1 $w.main.bc"
# Definition window (same as in Footer)
# must be placed after the pack commands
	text $w.main.umbra -bg #777777 -relief flat \
		-padx .4c -pady .2c -wrap word
	text $w.main.definition -bg #ffffcc -relief flat \
		-padx .4c -pady .2c -wrap word
	set font [lindex [lindex [$w.main.definition configure -font] end] 0]
	$w.main.definition configure -font {$font 10}
	$w.main.umbra configure -font {$font 10}
# Definition window - end
	if [info exists commonWords] {
		$w.main.bc.rep.h01.lb config -text <$homePath>
		$w.main.bc.rep.h02.lb config -text <$loCoInRep>
		UpdateMenu2 .window.main.bc.rep.h2.entry bcRepository bc(result1)
	}
}

# CreateMain - end
# ----------------------------------------------------------------------
# DisplayEditMetadata
# Example:
# DisplayEditMetadata $w.main.bc.rep.h2.entry.entry bcRepository bc(result1) #dddddd
# editMetadataState values are 0 or 1
# 1 means that the OK button has been press once
# 0 means that the OK button has not been press

proc DisplayEditMetadata {entryWidget entryName varName bg referenceType} {
# runs with start
	global defaultMetadataRepository
	global editMetadataState
	global ddChoice2
	upvar #0 $varName var
	set editMetadataState 0
# rep
	if ![regexp {^(.*/.*/.*/.*) .*} $var m rep] {
		regexp {^.* (.*/.*/.*/.*)} $var m rep
	}
	regexp {^..} $varName xx	;# dd or bc
	if [info exists rep] {
		if {[string compare dd $xx] == 0 && [string compare new $ddChoice2] == 0} {
# use the default metadata
			set rep {}
			set metadataRepList $defaultMetadataRepository
		} else {
#			set metadataRepList [FindMetadataRepList $rep $entryWidget $varName]
			set metadataRepList [lreverse [FindMetadataRepList $rep $entryWidget $varName]]	;# added by GJFB in 2015-12-19
		}
	} else {
		set rep {}
		set metadataRepList $defaultMetadataRepository
	}
	set buttonCursorState [SetWaitingState $entryWidget $xx]
	set n [llength $metadataRepList]
	set i $n
	foreach metadataRep $metadataRepList {
# puts $metadataRep
		set win .xxmetadata$i	;# .xxmetadata1
		if [Info exists repositoryProperties($metadataRep,language)] {
			set language [Get repositoryProperties($metadataRep,language)]
			set ref [lindex $language end]	;# [en]
		} else {
			set ref $i
		}	
		DisplayText $entryWidget $entryName $varName $win $bg \
		1 1 Cancel OK 1 $rep $metadataRep $ref $n \
		$buttonCursorState $referenceType
		incr i -1
	}
}

# DisplayEditMetadata
# ----------------------------------------------------------------------
# SetGeometry
# sets geometry for CreateMain, SPDialog and DDDialog procedures

proc SetGeometry {} {
# runs with start
	global w
		if {1024 <= [winfo screenwidth .]} {
		set width 368
#		set width 474	;# Linux
	} else {
		set width 270
	}
	if {[winfo screenheight .] == 768} {
		set height 450
	} elseif {[winfo screenheight .] == 864} {
# tap 11
		set height 450
	} elseif {900 <= [winfo screenheight .]} {
# tap 11 - 1080
#		set height 480
		set height 490
	} else {
		set height 341
	}
	wm geometry $w ${width}x$height+0+0
	wm minsize $w $width $height
	wm maxsize $w 800 $height
}

# SetGeometry - end
# ----------------------------------------------------------------------
# CloseMain

proc CloseMain {} {
# runs with start
	global bc
	global bcChoice1 bcReverse
	global bcSearch
	global bcSearchEntry
	global bcSearchResult
	global bcSelectedKeyRepList
	global bcSearchSelectMenu
	global bcRepositorySelectMenu
	global environmentArray
# if below is for migration 19/11/2000
	if [info exists bc(result1)] {set environmentArray(bcRepositoryEntry) $bc(result1)}
	if [info exists bcChoice1] {set environmentArray(bcChoice1) $bcChoice1}
	if [info exists bcReverse] {set environmentArray(bcReverse) $bcReverse}
	if [info exists bcSearch] {set environmentArray(bcSearch) $bcSearch}
	if [info exists bcSearchEntry] {set environmentArray(bcSearchEntry) $bcSearchEntry}
	if [info exists bcSearchResult] {set environmentArray(bcSearchResult) $bcSearchResult}
	if [info exists bcSelectedKeyRepList] {set environmentArray(bcSelectedKeyRepList) $bcSelectedKeyRepList}
#	if [info exists bcSearchSelectMenu] {set environmentArray(bcSearchSelectMenu) $bcSearchSelectMenu}
#	if [info exists bcRepositorySelectMenu] {set environmentArray(bcRepositorySelectMenu) $bcRepositorySelectMenu}
# SAVE
#	StoreArray environmentArray ../auxdoc/.environmentArray.tcl
#	StoreArray environmentArray ../auxdoc/.environmentArray2.tcl	;# backup
#	StoreArrayWithBackup environmentArray ../auxdoc/.environmentArray.tcl	;# added by GJFB in 2010-08-05
	StoreArrayWithBackup environmentArray ../auxdoc/.environmentArray.tcl w list	;# added by GJFB in 2010-08-05
# SAVE - end
}

# CloseMain - end
# ----------------------------------------------------------------------
# CreateEditMenu

proc CreateEditMenu {menu command} {
	global referenceTypeList
	$menu delete 0 end
	$menu add command -label {} \
		-command [concat $command [list {}]]
	foreach referenceType [lsort $referenceTypeList] {
		$menu add command -label $referenceType \
			-command [concat $command [list $referenceType]]
	}

}

# CreateEditMenu - end
# ----------------------------------------------------------------------
# UpdateCollection
# used by CreateRepMetadataRep, UpdateRepMetadataRep, InstallRepository and Run-ir
# updates repositoryProperties, referenceTable,
# multipleGlobalVariables and metadataArray for the
# repositories in repositoryList
# service -> repositoriesProperties array (-> metadataArray - see CreateExtraFields)
# service -> referenceTable array (-> metadataArray - see CreateExtraFields)
# @metadata.refer -> metadataArray
# flag values are 0 or 1; 1 means to save the metadata

proc UpdateCollection {repositoryList {flag 0}} {
# run with post
	global serverAddress
	global col
	global saveMetadata
	global homePath
	global URLibServiceRepository
	
Load $homePath/col/$URLibServiceRepository/auxdoc/@enableTrace enableTrace
TraceProcedure UpdateCollection
TraceProcedure	;# add executing time interval
TraceProcedure [clock format [clock seconds] -format %Y:%m.%d.%H.%M.%S]
TraceProcedure [CallTrace]

	set encodingSystem [encoding system]

	foreach rep $repositoryList {

		UpdateReferenceTable $rep	;# added by GJFB in 2018-12-25 - needed by ReturnRepositoryName below

		if [TestContentType $rep Metadata $homePath] {	;# added by GJFB in 2018-12-25 - CreateExtraFields below updates the target file name in metadataList based on repositoryProperties, consequently target file name must converted here otherwise the target file name may suffer the accent problem at repository migration
# $rep contains metadata
			if ![string equal {utf-8} $encodingSystem] {
# encoding system is not utf-8
				Load $col/$rep/service/encodingSystem encodingSystem2
				if [string equal {utf-8} $encodingSystem2] {
# service/encodingSystem was utf-8
# rep probably results from a migration
					set repName [ReturnRepositoryName $rep]
					if [file exists $homePath/col/$repName/service/targetFile] {
						Load $homePath/col/$repName/service/targetFile targetFile
						set targetFile [encoding convertfrom $encodingSystem2 $targetFile]	;# solves the accent problem when migrating from a collection using utf-8 encoding - e.g., migrating J8LNKAN8RW/34BETDS from plutao to banon-pc3
						Store targetFile $homePath/col/$repName/service/targetFile
					}
				}
			}
		}
	}
	
	foreach rep $repositoryList {
		UpdateRepositoryProperties $rep
#		UpdateReferenceTable $rep	;# commented by GJFB in 2018-12-25
		UpdateMultipleGlobalVariables $rep
	}
	
TraceProcedure	;# add executing time interval
TraceProcedure {arrays updated}
	
#	UpdateReferenceFileForLoCoInRep
#	StoreArray repositoryProperties ../auxdoc/.repositoryProperties.tcl
#	StoreArray referenceTable ../auxdoc/.referenceTable.tcl
	SaveRepositoryProperties
	
TraceProcedure	;# add executing time interval
TraceProcedure {repositoryProperties saved}
	
	SaveReferenceTable
	
TraceProcedure	;# add executing time interval
TraceProcedure {referenceTable saved}
	
TraceProcedure "repositoryList = $repositoryList"

	foreach rep $repositoryList {
		if [TestContentType $rep Metadata] {
# $rep contains metadata
			Load $col/$rep/doc/@metadata.refer fileContent
#			set encodingSystem [encoding system]
			Load $col/$rep/service/encodingSystem encodingSystem2
			if [string equal {utf-8} $encodingSystem] {
# encoding system is utf-8
				if ![string equal {utf-8} $encodingSystem2] {
# service/encodingSystem didn't exist (was not utf-8)
# the service/encodingSystem file must be updated or created
 					Store encodingSystem $col/$rep/service/encodingSystem	;# inform the local encoding system
				}
			} else {
# encoding system is not utf-8
				if [string equal {utf-8} $encodingSystem2] {
# service/encodingSystem was utf-8
# rep probably results from a migration
# code added by GJFB in 2010-11-23 - convertfrom utf-8 is NOT idempotent for all graphemes
					set fileContent [encoding convertfrom $encodingSystem2 $fileContent]	;# solves the accent problem when migrating from a collection using utf-8 encoding - e.g., migrating J8LNKAN8RW/34BETDS from plutao to banon-pc3
					set mtime [file mtime $col/$rep/doc/@metadata.refer]
					Store fileContent $col/$rep/doc/@metadata.refer
					file mtime $col/$rep/doc/@metadata.refer $mtime	;# restore mtime
					file delete $col/$rep/service/encodingSystem
				}
			}
			set metadataList [ConvertMultipleRefer2MetadataList 0 $fileContent $rep]
			set metadataList [concat $metadataList [CreateExtraFields $rep $serverAddress]]
TraceProcedure	;# add executing time interval
TraceProcedure {extra fields created}
# Add citationkey
			array set metadataImport $metadataList
			set citationkey [CreateCitationKey metadataImport $rep-0 1]
TraceProcedure	;# add executing time interval
TraceProcedure {citationkey created}
			set metadataList [concat $metadataList [list $rep-0,citationkey $citationkey]]
# Add citationkey - end
			set metadata2List [GetMetadata $rep-*]
			
# set xxx "metadata2List = --$metadata2List--"
# Store xxx C:/tmp/bbb.txt binary 0 a 
# set xxx "metadataList = --$metadataList--"
# Store xxx C:/tmp/bbb.txt binary 0 a 
TraceProcedure	;# add executing time interval
TraceProcedure {simplifying metadata...}
			SimplifyMetadataLists metadataList metadata2List
# REMOVE and ADD METADATA
TraceProcedure	;# add executing time interval
TraceProcedure {updating metadata...}
#			RemoveMetadata $metadata2List 0 $metadataList	;# commented by GJFB in 2020-08-18
TraceProcedure	;# add executing time interval
TraceProcedure {metadata removed}
#			AddMetadata $metadataList $metadata2List	;# commented by GJFB in 2020-08-18
TraceProcedure	;# add executing time interval
TraceProcedure {metadata added}

			UpdateMetadata $metadata2List $metadataList	;# added by GJFB in 2020-08-18 - uses metadata2List and metadataList
			
# Store metadataList C:/tmp/bbb.txt binary 0 a 
		}
		if [TestContentType $rep {Bibliography Data Base}] {
#			LoadBiblioDB $rep	;# commented by GJFB in 2013-01-05 to avoid time consuming LoadBiblioDB
			LoadBiblioDB $rep 1	;# 1 means to take into account the - signal (at the beginning of the file)
		}
		if [TestContentType $rep {CGI Script}] {
			InstallCGIScript $rep
		}
TraceProcedure	;# add executing time interval
TraceProcedure "$rep updated"
	}
	UpdateRepositoryListForPost $repositoryList
	if !$flag {return}
	set saveMetadata 1
	SaveMetadata
}

# UpdateCollection - end
# ----------------------------------------------------------------------
