#!/bin/sh
# Copyright for URLibService (c) 1995 - 2020,
# by Gerald Banon. All rights reserved.
# Version 2.1
# start (start the servers and open the main window)
# start -- -x (stop URLibService)

## start \
#exec ../../../../../\
#dpi.inpe.br/banon/1997/10.21.17.24\
#/doc/tk8.0/unix/wish "$0" ${1+"$@"}

# start \
exec /usr/local/bin/wish "$0" ${1+"$@"}

wm withdraw .

set URLibServiceRepository dpi.inpe.br/banon/1998/08.02.08.56
set devLoCoInRep dpi.inpe.br/banon/1999/01.09.22.14	;# used in DDRoutine
set downloadingEnvironmentRepository iconet.com.br/banon/2000/12.30.22.40
set applicationName start

set errorTrace 0	;# value is 0 or 1 - used in Submit (utilities1.tcl) when running UpdateKeyRepositoryList

# Description of some global variable
# w	;# main window name
# languageList	;# list of available languages
# browserList	;# list of available browsers
# languageTable	;# the values are repository names
# mirrorLanguageTable	;# the values are repository names
# webLanguageTable	;# the values are en, pt-BR, ...
# keyRepositoryList	;# list of identification keys and repositories
# environmentArray	;#
# referenceTable	;#
# repositoryProperties	;# history, targetfile, type
# conversionTable	;# for refer format of EndNote
# orderingTable	;# for refer format of EndNote
# inverseTable	;# for refer format of EndNote
## dateFieldPattern	;# month|issuedate|date|lastupdatedate
# (created in StartService and not used)
# metadataArray	;# indices are rep-i's and field names
# repArray	;# contains repository names, index is word,field
# authorArray	;# contains author names, index is word,field
# groupArray	;# contains group names, index is word,field
# committeeArray	;# contains names of committee members, index is word,field
# journalArray	;# contains journal names, index is word,field
# conferencenameArray	;# contains conference names, index is word,field
# wordOccurrenceArray	;# contains number of words, index is word
# mostRecentReferences	;# contains the most recent references
# mostRecentFullTexts	;# contains the most recent full texts
# saveMetadata	;# values are 0 or 1; 1 means save
# bannerPathArray ;# array of pathes for repositories whose service/type is Banner - indices are banner languages
# bannerSequenceRepList	;# list of repositories whose service/type is Banner Sequence
# officialIconRepList ;# list of repositories whose service/type is Access Icon, but not the default icon
# log	;# text widget name
# textLog	;# text log
# spPreferenceButton	;# values are language, mail, ...
# spPreference	;# values are spLanguage, spMail, ...
# spDaylightTime
# spDocPermission1
# spDownloadPermission1
# spDocPermission2
# spDownloadPermission2
# spDocPermission3
# spDownloadPermission3
# spDocAccessPermission
# spDownloadAccessPermission
## spPermissionText
# ddDirectory	;# value is ddDirectory
# ddRepository	;# value is ddRepository
# ddChoice2	;# values are new or repository
## spDialogLanguage	;# language used to construct the dialog
# ddDialogLanguage	;# language used to construct the dialog
# wDialogLanguage	;# language used to construct the dialog
# spSettingArray	;# contains the settings before OK is completed
## spArrayName	;# values are environmentArray or spSettingArray
# hostName		;# banon-pc
# domainName	;# dpi.inpe.br
# homePath	;# ex: /home/URLib
# col
# URLibServiceRepository
# URLibBannerSequenceRepository
# zipPath
# zipRepository
# unZipPath
# unZipRepository
# englishRepository
# citationKeyRepository
# serverAddress	;# banon-pc.dpi.inpe.br 19050
# serverAddressWithIP	;# 150.163.2.174 19050
# localSite	;# banon-pc.dpi.inpe.br:1905 - used in Link
# tclRepository
# tclExec	;# ex: bin/tclsh81.exe
# apacheRepository
# searchRepository
# compileWordsRepository
# referRepository
# bib2referRepository
# englishMirrorRepository
# defaultMetadataRepository
# defaultDocRepository
# defaultAccessIconRepository
# mirrorHomePageRepository
# copyrightWarningRepository
# ddSearchResult	;# contains a repository list; search result done dd form
# ddSelectedkeyRepList	;# list of selected identification keys and repositories
# loCoInRep	;# == environmentArray(localCollectionIndexRepository)
# loBiMiRep	;# == environmentArray(localBibliographicMirrorRepository)
# commonWordsRepList	;# contains a repository list
# commonWords ;# contains a list of common words
# localURLibClientSocketId
# localURLibServer	;# array
# mirrorPage	;# defined in utilities1.tcl, used in StartServer.tcl and mirror.tcl
## fieldNamePattern ;# used in MountSearch
# fieldNameList ;# created in StartService and used in MountSearch
## startService	;# 0 or 1; 1 means that StartService must be executed
## globalFileContent	;# used to work with namespace (StartService)
## processID	;# {time} {integer}, used in Find-
# loginSeconds	;# set in start script only
## LoginDone	;# used in CreateMainWindow
## ddDepositing	;# used in DDCancel (DDDialog.tcl)
# spButtonList	;# values are: language mail browser port
# fieldNameArray	;# defines field names for metadata, service and repositoryProperties
# startApacheServer ;# values are 0 or 1; 1 means Apache must be started
# applicationName	;# values are: start or post
# installInitialCollection	;# values are 0 or 1; 1 means installation - defined in start and post
## posted	;# values are 0 or 1; 1 means posted
# setPreferences	;# values are 0 or 1; 1 means set preference; set by SPOK and SPCancel, and used by start
## permText	;# permission text (SPDialog.tcl)
# editorPath
# urlibEnvironment	;# list of repositories part of the URLibService Environment
# urlibServiceVersion ;# extracted from the history of the URlibService Repository; set in StartService
## OAISetSpecification	;# set in UpdateOAIRepositoryData
# doubleClickFlag	;# used only in ExecuteWish and Edit (utilities2.tcl)

# global variables needed for start
# applicationName	;# values are: start or post
# editMetadataState	;# values are: 0 or 1
# endNoteRepository
# citationKeyRepository
# col
# commonWords
# defaultAccessIconRepository
# defaultDocRepository
# dd.dirPostMenu
# dd.repPostMenu
# ddChoice1
# ddChoice2	;# values are new or repository
# ddChoice3
# ddDirectory	;# value is ddDirectory
# ddRepository	;# value is ddRepository
# ddReverse
# ddSearchEntry
# ddSearchResult	;# contains a repository list; search result done dd form
# ddSelectedkeyRepList	;# list of selected identification keys and repositories
# dialogRunning	;# used to control the cursor aspect
# displayMessageId1	;# set in DisplayMessage
# displayMessageId2	;# set in DisplayMessage
# displayMessage	;# set in DisplayMessage
# editorPath
# environmentArray
# fieldNameArray	;# used in UpdateField
# homePath
# installInitialCollection	;# used in Cancel
# inverseTable
# keyRepositoryList
# languageList	;# list of available languages
# languageTable	;# the values are repository names
# listNameTable	;# defined in DDDialog
# loBiMiRep
# localSite	;# banon-pc.dpi.inpe.br:1905 - used in Link
# localURLibClientSocketId
# loCoInRep
# log	;# created in CreateMain
# mirrorLanguageConversionTable	;# created in SourceLanguage
# mirrorLanguageTable	;# the values are repository names
# performCheckRunning	;# used to control the cursor aspect
## posted
# pwd
# referenceTypeList
# referRepository
# ${referRepository}::conversionTable
# returnDialog
# searchRepository
# serverAddress	;# banon-pc.dpi.inpe.br 19050
# serverAddressWithIP	;# 150.163.2.174 19050
# serverRoot	;# for Apache
# setPreferences	;# values are 0 or 1; 1 means set preference; set by SPOK and SPCancel, and used by start
# Text::
# tclExec	;# ex: bin/tclsh81.exe
# tclRepository
# typeTable	;# defined in DDDialog
# unZipPath
# unZipRepository
# updateTargetFileRunning	;# used to control the cursor aspect
# URLibBannerSequenceRepository
# urlibEnvironment	;# list of repositories part of the URLibService Environment
# URLibServiceRepository
# urlibServiceVersion ;# extracted from the history of the URlibService Repository; set in StartService
# w	;# main window name
# webLanguageTable	;# the values are en, pt-BR, ...
# zipPath
# zipRepository


# global variables not needed for start
# bannerPathArray ;# array of pathes for repositories whose service/type is Banner - indices are banner languages
# bannerSequenceRepList	;# list of repositories whose service/type is Banner Sequence
# metadataArray
# referenceTable
# repositoryProperties
# saveMetadata
# startApacheServer
# tokenCounter	;# set in RemoteExecute
## processCounter	;# set in CreateProcessID


# URLibService needs the following repositories:
# to capture this list click in Parent Repositories > OK
# close/start is needed to have the urlibEnvironment (in ControlBCButtonState - utilities2.tcl) variable updated
# ../../../../../../col/dpi.inpe.br/banon/1999/07.11.21.09 (citationKeyRepository - Creating the citation key - CreateKey)
# ../../../../../../col/dpi.inpe.br/banon/1999/04.21.17.06 (searchRepository - Fast lookup in bibliography data bases - Search)
# ../../../../../../col/dpi.inpe.br/banon/1999/08.08.19.14 (referRepository - Ordering and conversion tables for the Refer format)
# ../../../../../../col/iconet.com.br/banon/2003/04.18.13.10 (BibINPERepository - BibINPE style sheet)
# ../../../../../../col/dpi.inpe.br/banon/1999/07.17.00.02 (bib2referRepository - Converting BibTeX to Refer)
# ../../../../../../col/dpi.inpe.br/banon/1999/04.25.14.34 (compileWordsRepository - Common words compiler)
# ../../../../../../col/dpi.inpe.br/banon/1998/05.03.10.10 (englishRepository - English version of URLibService)
# ../../../../../../col/dpi.inpe.br/banon/1999/04.25.10.22 (englishWordsRepository - English common words)
# ../../../../../../col/dpi.inpe.br/banon/1999/05.03.22.11 (englishMirrorRepository - English version of the mirror pages)
## ../../../../../dpi.inpe.br/banon/1999/09.12.15.10 (defaultMetadataRepository - Default metadata)
## ../../../../../dpi.inpe.br/banon/1999/09.12.15.17 (metadata repository for the Default metadata)
## ../../../../../dpi.inpe.br/banon/1999/09.19.18.20 (defaultDocRepository - Default document)
## ../../../../../dpi.inpe.br/banon/1999/09.19.22.25 (metadata repository for the Default document)
# ../../../../../../col/dpi.inpe.br/banon/1999/12.15.21.29 (Default access icon)
# ../../../../../../col/dpi.inpe.br/banon/2000/01.23.20.24 (mirrorHomePageRepository - Mirror home page)
# ../../../../../../col/dpi.inpe.br/banon/2000/02.05.09.57 (URLibBannerSequenceRepository)
# ../../../../../../col/dpi.inpe.br/banon/2000/02.20.10.08 (copyrightWarningRepository)
## ../../../../../iconet.com.br/banon/2000/12.31.20.38 (URLibService User's Guide)
# ../../../../../../col/iconet.com.br/banon/2001/02.10.22.55 (What is URLib?)
# ../../../../../../col/iconet.com.br/banon/2001/05.25.16.44 (O que é a URLib?)
# ../../../../../../col/iconet.com.br/banon/2001/11.24.08.30 (Parsing full name)
# ../../../../../../col/iconet.com.br/banon/2001/11.04.16.39 (File sampling)
## ../../../../../../iconet.com.br/banon/2003/05.31.10.26 (INPE submission forms)
## ../../../../../../iconet.com.br/banon/2003/05.31.10.38 (English version of the INPE submission forms)
## ../../../../../../iconet.com.br/banon/2003/05.31.10.45 (Portuguese/Brazil version of the INPE submission forms)
# ../../../../../../col/iconet.com.br/banon/2004/11.15.21.08 (Xrefer metadata creation)
# ../../../../../../col/dpi.inpe.br/banon-pc@1905/2005/02.19.00.40 (Administrator page)
# ../../../../../../col/iconet.com.br/lise/2005/06.25.14.21 (Send mail)
# ../../../../../../col/iconet.com.br/banon/2003/11.21.21.08 (Open Archives Initiative Protocol Implementation)
# ../../../../../../col/dpi.inpe.br/banon-pc2@1905/2006/02.16.12.09 (A service returning a table containing selected metadata)
# ../../../../../../col/dpi.inpe.br/banon-pc3@80/2010/02.03.13.25 (Inflection program)
# ../../../../../../col/urlib.net/www/2014/03.16.03.40 (A Service returning a list of ibi properties)
# ../../../../../../col/iconet.com.br/banon/2006/07.02.02.18 (Administrator page for customizing the conference submission forms)

# For Windows platform it needs:
# ../../../../../dpi.inpe.br/banon/1998/05.17.16.22 (tclRepository - Tcl/Tk 8.0.p2 for Windows, Binary Distribution)
# ../../../../../dpi.inpe.br/banon/2000/07.11.18.24 (tclRepository - Tcl/Tk 8.3.1 for Windows, Binary Distribution)
# ../../../../../dpi.inpe.br/banon/1999/01.02.16.35 (apacheRepository - Apache HTTP Server Version 1.3 for Windows)
## ../../../../../dpi.inpe.br/banon/1998/03.07.08.57 (zipRepository - Zip 2.2 - Windows 95 version)
## ../../../../../dpi.inpe.br/banon/2000/08.09.16.24 (unZipRepository - UnZip 5.4 - Windows 95 version)
# ../../../../../urlib.net/www/2010/12.28.21.01 (zipRepository - Zip 3.0 - Windows version)
# ../../../../../urlib.net/www/2010/12.28.21.51 (unZipRepository - UnZip 6.0 - Windows version)

# For UNIX platform it needs:
# ../../../../../dpi.inpe.br/banon/1997/10.21.17.24 (tclRepository - Tcl/Tk 8.1.1 for SunOS 5.5.1)
# ../../../../../dpi.inpe.br/banon/2000/07.19.17.47 (tclRepository - Tcl/Tk 8.3.0 for sparc 5.7)
# ../../../../../dpi.inpe.br/vagner/1999/07.16.16.29 (apacheRepository - Apache HTTP Server Version 1.3 for Solaris)
# ../../../../../dpi.inpe.br/vagner/1999/07.22.16.12 (zipRepository - Zip 2.2 - Solaris/SunOS version)
# ../../../../../dpi.inpe.br/banon/2000/08.09.17.10 (unZipRepository - UnZip 5.32 - Solaris version)

# add portuguese
# ../../../../../../col/dpi.inpe.br/banon/1999/05.01.15.35 (Portuguese common words)
# ../../../../../../col/dpi.inpe.br/banon/1998/07.26.10.08 (Portuguese/Brazil version of URLibService)
# ../../../../../../col/dpi.inpe.br/banon/1999/06.19.22.43 (Portuguese/Brazil version of the default mirror pages)
# ../../../../../../col/dpi.inpe.br/banon/2000/02.20.10.44 (Aviso de direitos autorais de default para o acervo da URLib)
# add french
# ../../../../../../col/dpi.inpe.br/banon/1999/05.01.14.16 (French common words)

# copyright
# ../../../../../../col/dpi.inpe.br/banon/2000/03.04.00.05 (URLibService Copyright)
## ../../../../../dpi.inpe.br/banon/2000/08.09.18.00 (Zip 2.2 licence)
## ../../../../../dpi.inpe.br/banon/2000/08.09.18.17 (UnZip 5.4 licence)
# ../../../../../../col/dpi.inpe.br/banon-pc3/2010/12.30.12.00 (Info-ZIP license)
## ../../../../../iconet.com.br/banon/2003/12.26.17.58 (Tcl/Tk 8.4.4 licence)
# ../../../../../../col/iconet.com.br/banon/2001/12.30.16.31 (The Apache Software Licence, Version 1.1)

# set processID [list [clock seconds] 0]

if ![regexp "(^.*)/col/$URLibServiceRepository/doc" [pwd] m homePath] {
# starting from home
	cd col/$URLibServiceRepository/doc
	regexp "(^.*)/col/$URLibServiceRepository/doc" [pwd] m homePath
}
# homePath, ex: /home/URLib

set applicationNameForReverseEngineering start	;# for reverse engineering only
set applicationRuningTime [clock format [clock seconds] -format %Y:%m.%d.%H.%M.%S]	;# for reverse engineering only
set applicationFileName "'$homePath/col/$URLibServiceRepository/doc/start'"	;# for reverse engineering only

set pwd [pwd]

## Correct accent (some unzip program don't preserve original accent at installation)
#if ![file exists $homePath/col/dpi.inpe.br/banon/1998/07.26.10.08/doc/PortuguêsLanguage.tcl] {
#	set fileName [join [glob $homePath/col/dpi.inpe.br/banon/1998/07.26.10.08/doc/Portugu?sLanguage.tcl]]
#	file rename $fileName $homePath/col/dpi.inpe.br/banon/1998/07.26.10.08/doc/PortuguêsLanguage.tcl
#}
## Correct accent - end

# serverRoot
if [file exist $homePath/readOnlySite] {
	set serverRoot C:/tmp/URLib/Apache/serverDir 
	file mkdir $serverRoot
} else {
	set serverRoot $homePath/col/$URLibServiceRepository/auxdoc/serverDir
}

# ----------------------------------------------------------------------
proc FindProcType {procName} {
	global calledProcTable
	global procTypeTable
	global propagateTable
	upvar auxList auxList
	lappend auxList $procName
	if $propagateTable($procName) {return $procTypeTable($procName)}
	if {$procTypeTable($procName) == "tk"} {return tk}
	foreach proc $calledProcTable($procName) {
		if {$procTypeTable($proc) == "tk"} {return tk}
		if {[lsearch -exact $auxList $proc] != -1} {continue}	;# recurrent procedure
		set procType [FindProcType $proc]
		if {$procType == "tk"} {return tk}
	}
	return tcl
}

proc FindGlobal {procName} {
	global calledProcTable
	global procTypeTable
	global procPropagateTypeTable
	global propagateTable
	global globalTable
	upvar auxList auxList
	lappend auxList $procName
	if $propagateTable($procName) {return $globalTable($procName)}
	if {$procPropagateTypeTable($procName) == "tk" && $globalTable($procName)} {return 1}
	if {$procTypeTable($procName) == "tcl" && $globalTable($procName)} {return 1}
	foreach proc $calledProcTable($procName) {
		if {$procTypeTable($proc) == "tk"} {continue}
		if {[lsearch -exact $auxList $proc] != -1} {continue}	;# recurrent procedure
		if {$globalTable($proc)} {return 1}	;# true tcl with global
		if [FindGlobal $proc] {return 1}
	}
	return 0
}

lappend auto_path $pwd
package require $URLibServiceRepository

if [file isdirectory $homePath/col/$devLoCoInRep] {
# The command below should be run only during the development process
#	eval "pkg_mkIndex . $tclFileList"

	if {$tcl_platform(platform) == "windows"} {
		if 1 {console hide} else {console show}
# >>> Create procedureList, numberOfCodeLines and procedureList3
		if 0 {
			set tclFileList {}
			set path $homePath/col/dpi.inpe.br/banon/1998/08.02.08.56/doc
			source $path/utilities1.tcl	;# set DirectoryContent		
			DirectoryContent tclFileList $path $path
			set i [lsearch $tclFileList .htaccess]
			set tclFileList [lreplace $tclFileList $i $i]
			set i [lsearch $tclFileList post]
			set tclFileList [lreplace $tclFileList $i $i]
			set i [lsearch $tclFileList start]
			set tclFileList [lreplace $tclFileList $i $i]
	 
# create procedureList and numberOfCodeLines files
			set numberOfCodeLines 0
			set fileId [open procedureList w]
			foreach tclFile $tclFileList {
				if {$tclFile == "definition.tcl"} {continue}
if 0 {
# old code
				Load $tclFile fileContent
				regsub -all {@} $fileContent {#!#} entry	;# @ > #!#
				regsub -all "\nproc " $entry {@} entry
				puts $fileId "--- $tclFile ---"
				foreach proc [lrange [split $entry @] 1 end] {
					regexp {[^ ]+} $proc procName
					lappend procList $procName
					puts $fileId $procName					
				}
				puts $fileId ""
} else {
# new code
				interp create slave
				if [catch {interp eval slave [list source $tclFile]}] {interp delete slave; continue}
				set procList [lsort -dictionary [interp eval slave {info procs {[A-Z]*}}]]
				
				puts $fileId "--- $tclFile ---"
				foreach proc $procList {
					puts $fileId $proc					
					set lineList {}
					foreach line [split [string trim [interp eval slave "info body $proc"]] \n\;] {
						if ![regexp {^(#|\s*$)} $line] {	;# drop the comment and blank lines
							lappend lineList $line
						}
					}
					incr numberOfCodeLines [llength $lineList]
				}
				interp delete slave
				puts $fileId ""
}
			}
			close $fileId
			
			set fileId [open numberOfCodeLines w]
			puts $fileId "--- $numberOfCodeLines ---"
			close $fileId
			
if 0 {
# update procedureList3 - should be improved
			set procList [lsort -dictionary $procList]
			foreach proc1 $procList {
				set body [info body $proc1]
# drop the comments
				set itemList {}
				foreach item [split $body \n\;] {
					if ![regexp {^#} $item] {
						lappend itemList $item
					}
				}
				set body [join $itemList]
# drop the comments - end
				set calledProcList {}
				foreach proc2 $procList {
					set argList [info args $proc2]
					if {$argList == {}} {
						set pattern $proc2
					} else {
						set firstArg [lindex $argList 0]
						if [info default $proc2 $firstArg v] {
							set pattern $proc2
						} else {
							set pattern "$proc2 "
						}
					}
# if [regexp {^Array} $pattern] {puts --$pattern--}
					regsub -all "list $pattern|Dialog $pattern" $body {} body
					if [regexp "\[^a-zA-Z0-9\]$pattern" $body] {
						lappend calledProcList $proc2
					}
				}
				set calledProcList [lsort -dictionary $calledProcList]
				set calledProcTable($proc1) $calledProcList
			}
			set fileId [open procedureList3 w]
			foreach proc1 $procList {
				puts $fileId "--- $proc1 ---"
				set callingProcList {}
				foreach proc2 $procList {
					if {[lsearch -exact $calledProcTable($proc2) $proc1] != "-1"} {
						lappend callingProcList $proc2
					}
				}
				puts $fileId $callingProcList
				puts $fileId ""
			}
			close $fileId
}
		}
# Create procedureList, numberOfCodeLines and procedureList3 - end
	} 
}
# console show
# ----------------------------------------------------------------------

# tkwait is to start the console display
# catch {tkwait visibility .}
# after 4000 exit

if ![file isdirectory ../auxdoc] {
	file mkdir ../auxdoc	;# for installation
}

set empty {}
if ![file exists ../auxdoc/netscape.txt] {
	Store empty ../auxdoc/netscape.txt
}
if {$tcl_platform(platform) == "windows"} {
	if ![file exists ../auxdoc/mozilla.txt] {
		Store empty ../auxdoc/mozilla.txt
	}
	if ![file exists ../auxdoc/internetExplorer.txt] {
		Store empty ../auxdoc/internetExplorer.txt
	}
	if ![file exists ../auxdoc/chrome.txt] {
		Store empty ../auxdoc/chrome.txt
	}
}
if {$tcl_platform(platform) == "unix"} {
	if ![file exists ../auxdoc/hotjava.txt] {
		Store empty ../auxdoc/hotjava.txt
	}
}
if ![file exists ../auxdoc/editor.txt] {
	Store empty ../auxdoc/editor.txt
}

# Load global variables
## installInitialCollection doesn't exist
# LoadGlobalVariables 0	;# sources environmentArray
LoadGlobalVariables	;# sources environmentArray - sets installInitialCollection
# Load global variables - end

if 0 {
# Extract a new version of URLibService
source ExtractURLibService.tcl
ExtractURLibService
# Extract a new version of URLibService - end
}

if 0 {
# not used because GetUserData is not used with noMatch == 1 with start
if [file exists $homePath/col/$searchRepository] {
#	lappend auto_path $homePath/col/$searchRepository/doc
#	package require $searchRepository
	source $homePath/col/$searchRepository/doc/Search.tcl	;# SetNoMatch is used in GetUserData
}
}

# endNoteRepository
set endNoteRepository dpi.inpe.br/banon/1999/08.14.20.04

file mkdir ../$col/clipboard	;# used by LoadMetadata

if [regexp -- {-[xX]} $argv] {
	Run-exit
}

if [regexp -- {-[rR]} $argv] {
# reset (may be necessary after a "disk quota exceeded")
	file delete ../auxdoc/.repositoryProperties.tcl
	file delete ../auxdoc/.referenceTable.tcl
	file delete ../auxdoc/.wordOccurrenceArray.tcl
	file delete ../auxdoc/.keyRepositoryList.tcl
}

if {![info exists environmentArray(spLanguageEntry)] || \
	![info exists environmentArray(serviceLanguageRepository)]} {
	set environmentArray(spLanguageEntry) English
	set environmentArray(serviceLanguageRepository) $englishRepository
}

SourceLanguage environmentArray

# Create browserList
set browserList {}
if {$tcl_platform(platform) == "windows"} {
	if ![FindBrowser netscape] {lappend browserList {Netscape}}
	if ![FindBrowser mozilla] {lappend browserList {Mozilla}}
	if ![FindBrowser internetExplorer] {lappend browserList {Internet Explorer}}
	if ![FindBrowser chrome] {lappend browserList {Chrome}}
}
if {$tcl_platform(platform) == "unix"} {
	if {$tcl_platform(os) == "SunOS"} {
		if ![FindBrowser netscape] {lappend browserList {Netscape}}
		if ![FindBrowser hotjava] {lappend browserList {HotJava}}
	}
	if {$tcl_platform(os) == "Linux"} {
		if ![FindBrowser netscape] {lappend browserList {Netscape}}
		if ![FindBrowser mozilla] {lappend browserList {Mozilla}}
		if ![FindBrowser konqueror] {lappend browserList {Konqueror}}
	}
}
# Create browserList - end

if [file exists ../auxdoc/messageForStart] {file delete ../auxdoc/messageForStart}

if 0 {
# comented by GJFB in 2016-04-28 - now in LoadGlobalVariables
if [info exists environmentArray(localCollectionIndexRepository)] {
# environmentArray is sourced in LoadGlobalVariables (see above)
	set installInitialCollection 0
} else {
	set installInitialCollection 1
}
}

# puts $installInitialCollection 

if $installInitialCollection {
	set setPreferences 1
# Create repositoryList
	cd $homePath/col
	set repositoryList [glob -nocomplain */*/*/*]
	cd $pwd
# Create repositoryList - end
	foreach rep $repositoryList {
		UpdateRepositoryProperties $rep
		UpdateReferenceTable $rep 0
	}
# Create languageList and languageTable
	array set languageTable [CreateLanguageTable]
	set languageList [array names languageTable]
# Create languageList and languageTable - end
	FindInternetAddress	;# updates environmentArray	- placed here by GJFB in 2010-08-13 - previously in SPOK
#	if [string equal {} $environmentArray(domainName)] {
#		Dialog OK disabled -1 Start {domain name not found}	;# commented by GJFB in 2017-10-15
#		exit
#	}
	if [catch {Execute urlib.net GetURLibServiceSiteWithIP} urlibServiceSiteWithIP] {
		set log {urlib.net site not found}
		StoreLog {alert} {start} $log	;# added by GJFB in 2021-07-07
		Dialog OK disabled -1 Start {urlib.net site not found}	;# added by GJFB in 2017-10-15 - urlib.net site not found: computer probably in standalone mode
		exit
	} elseif [string equal {} $urlibServiceSiteWithIP] {
			set log {urlib.net site not found}
			StoreLog {alert} {start} $log	;# added by GJFB in 2021-07-07
			Dialog OK disabled -1 Start {urlib.net site not found}	;# added by GJFB in 2017-10-15 - urlib.net site not found: computer probably in standalone mode
			exit
	}		
	set serverAddress {} 
} else {
	set setPreferences 0
	set serverAddress [GetServerAddress]
	set serverAddressWithIP [GetServerAddress 1]
	set localSite [ReturnHTTPHost]
}

# set unPosted [catch {Execute $serverAddressWithIP "GetValue startApplicationInUse"}]
# set unPosted [MultipleExecute [list $serverAddressWithIP] [list list Identity 0]]
# empty or 0
set unPosted [catch {Execute $serverAddressWithIP [list TestExecute x] 0}]	;# not async, in order to return without waiting for writing time out
# puts $unPosted
if $unPosted {
# URLib server is not running
#	set serverRoot $homePath/col/$URLibServiceRepository/auxdoc/serverDir
	if [file exists $serverRoot/logs/httpd.pid] {
		StopApacheServer2 $serverRoot
		file delete $serverRoot/logs/virtualHostRunning
	}
} else {
# URLib server is running
	if [Info exists startApplicationInUse] {
		if ![regexp -- {-[fF]} $argv] {	;# if added by GJFB in 2024-04-04 to force opening the main window - useful with SSH when the console becomes inactive
			Dialog OK disabled -1 Start {URLibService running}
			exit
		}
	}
}

# puts [winfo screenwidth .]
# puts [winfo screenheight .]
# return

CreateMainWindow	;# set log

if 0 {tkwait visibility $w; Run-sp; return}

if [file exists $homePath/newVersion] {
	if {[info exists loCoInRep] && $loCoInRep != "$devLoCoInRep"} {
		if [file exist ../auxdoc/.urlibServiceVersion.tcl] {
			source ../auxdoc/.urlibServiceVersion.tcl	;# set urlibServiceVersion
		} else {
			set urlibServiceVersion 0
		}
		source $homePath/newVersion	;# set updateLevel 
		if {[string compare $updateLevel(1) $urlibServiceVersion] > 0} {
# old version - delete textlog
			file delete ../auxdoc/textLog
		}
	}
}

# Set login time and date
# set loginSeconds [GetSeconds]
set loginSeconds [clock seconds]
set weekday [clock format $loginSeconds -format %a]
set month [clock format $loginSeconds -format %b]
set day [clock format $loginSeconds -format %d]
set time [clock format $loginSeconds -format %T]
set year [clock format $loginSeconds -format %Y]
LogInsert [list [list Insert $log insert {new line}]] 1 0 0
LogInsert [list [list Insert $log end \
	{login time: $var1 $var2 $var3 $var4  $var5} \
	{} $weekday $month $day $time $year]] 0 0 0
LogInsert [list [list Insert $log insert {new line}]] 0 1 0
# Set login time and date - end

while {$setPreferences || ![info exists environmentArray(spMailEntry)]} {
	set x 0; after 100 {set x 1}; vwait x
}

DisplayTextLog

if $unPosted {
# post is not running
	LogInsert [list [list Insert $log insert {new line}]]
	LogInsert [list [list Insert $log end {posting the URLib local collection ...}]]
	LogInsert [list [list Insert $log insert {new line}]]
# 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

# POST THE LOCAL COLLECTION
	set message [PostLocalCollection]	;# returns the messageForStart
# puts --$message--
# POST THE LOCAL COLLECTION - end

	if ![regexp {URLib local collection posted} $message] {
# not posted
		if [regexp {access not completed} $message] {
			foreach {serverName urlibPort} [ReturnCommunicationAddress $serverAddressWithIP] {break}
			Dialog OK disabled -1 Start $message $serverName $urlibPort
		} else {
			Dialog OK disabled -1 Start $message
		}
		LogInsert [list [list Insert $log insert {new line}]] 1 0
		LogInsert [list [list Insert $log end {URLib local collection not posted}]] 0 0
		LogInsert [list [list Insert $log insert {new line}]] 0 1
		if {[info exists w] && [winfo exist $w]} {wm withdraw $w}
		exit
	}

if 0 {
# unsets below are needed because the internet address might have been changed
	if [info exists environmentArray(hostName)] {
		unset environmentArray(hostName)
	}
	if [info exists environmentArray(domainName)] {
		unset environmentArray(domainName)
	}
}
# RELOAD
# needed because the internet address might have been changed
# FindInternetAddress in post might update environmentArray
#	source ../auxdoc/.environmentArray.tcl
	SourceWithBackup ../auxdoc/.environmentArray.tcl environmentArray	;# added by GJFB in 2010-08-05
# RELOAD - end

# serverAddress (might have been changed)
	set serverAddress [GetServerAddress]
	set serverAddressWithIP [GetServerAddress 1]
	set localSite [ReturnHTTPHost]

	if $installInitialCollection {
		set loCoInRep $environmentArray(localCollectionIndexRepository)
		set loBiMiRep $environmentArray(localBibliographicMirrorRepository)
	}
	LogInsert [list [list Insert $log insert {new line}]] 1 0
	LogInsert [list [list Insert $log end {URLib local collection posted}]] 0 0
	LogInsert [list [list Insert $log insert {new line}]] 0 1
}

# >>> at installation, at this stage registration of the new local collection has been completed at urlib.net (in col/dpi.inpe.br/banon/2004/02.16.09.30.00/auxdoc/localCollectionPasswordArray.tcl the entry {} has been changed to loCoInRep - see CreateIBI)

Set startApplicationInUse 1	;# could be anything

# Create languageList and languageTable
if !$installInitialCollection {
	array set languageTable [Eval CreateLanguageTable]
	set languageList [array names languageTable]
}
# Create languageList and languageTable - end

# Create commonWords
# needs post running
set commonWords [${compileWordsRepository}::CompileWords \
	[Eval CreateCommonWordsRepList]]
# Create commonWords - end

# Create the keyRepositoryList
# just used by start ... but needs post running
# AddKey may call ReturnType which need metadataArray
if [file exists ../auxdoc/.keyRepositoryList.tcl] {
	if [catch {source ../auxdoc/.keyRepositoryList.tcl}] {
		file delete ../auxdoc/.keyRepositoryList.tcl
	}
}
# Create the keyRepositoryList - end

# Create or update keyRepositoryList
set repositoryListForStart {}
if [file exists ../auxdoc/.repositoryListForStart.tcl] {
	source ../auxdoc/.repositoryListForStart.tcl	;# set repositoryListForStart
}
# puts [file exists ../auxdoc/.keyRepositoryList.tcl]
if ![file exists $homePath/col/$loCoInRep/auxdoc/xxx] {
# old code
if {![file exists ../auxdoc/.keyRepositoryList.tcl] || ![string equal {} $repositoryListForStart]} {
	if ![file exists ../auxdoc/.keyRepositoryList.tcl] {
		if $installInitialCollection {unset repositoryList}	;# must be updated - doesn't contain the loCoInRep and loBiMiRep, and their metadata repositories
		CreateRepositoryList
		set repositoryList2 $repositoryList
	} else {
		set repositoryList2 $repositoryListForStart
	}
	foreach rep $repositoryList2 {
		UpdateKeyRepositoryList $rep
	}
	StoreList keyRepositoryList ../auxdoc/.keyRepositoryList.tcl
}
} else {
# new code (faster)
	if ![file exists ../auxdoc/.keyRepositoryList.tcl] {
		Load $homePath/col/$loCoInRep/auxdoc/xxx data binary
		set data [UnShift $data]
		set administratorCodedPassword [lindex $data end]
		set keyRepositoryList [MultipleEval Select2 {citationkey repository} {repository, *} $administratorCodedPassword]
		set rep-iList [MultipleEval GetMetadataRepositories {} 0 {repository, *} no no 1 {} repArray $administratorCodedPassword]
		foreach rep-i ${rep-iList} {
#			regexp {(.*)-([^-]*)$} ${rep-i} m metadataRep i
			regsub -- {-[^-]*$} ${rep-i} {} metadataRep
			lappend keyRepositoryList [list :metadata.cgi: $metadataRep]
		}
		StoreList keyRepositoryList ../auxdoc/.keyRepositoryList.tcl
	} elseif {![string equal {} $repositoryListForStart]} {
		foreach rep $repositoryListForStart {
			UpdateKeyRepositoryList $rep
		}
		StoreList keyRepositoryList ../auxdoc/.keyRepositoryList.tcl
	}
}
file delete ../auxdoc/.repositoryListForStart.tcl
# Create or update keyRepositoryList - end

# Update URLibService
# see also StartService
if [info exists updateLevel] {
# Update keyRepositoryList, and add the auxdoc and source directories
	Load $homePath/packedRepository packedRepository
	if [string equal $URLibServiceRepository $packedRepository] {
# packedRepository is URLibServiceRepository
		Load $homePath/repositoryList repList2
		set storeKeyRepositoryListFlag 0
		foreach rep $repList2 {
			set storeKeyRepositoryListFlag [UpdateKeyRepositoryList $rep $storeKeyRepositoryListFlag]
			file mkdir $homePath/col/$rep/auxdoc
			file mkdir $homePath/col/$rep/source
		}
		if $storeKeyRepositoryListFlag {
			StoreList keyRepositoryList ../auxdoc/.keyRepositoryList.tcl
		}
	}
# Update keyRepositoryList, and add the auxdoc and source directories - end
}
# Update URLibService - end


#if {$loCoInRep != "$devLoCoInRep"} {
#	file delete $homePath/newVersion
#}

# next line must be run after the collection has been posted
# CompleteEntry $w.main.bc.rep.f.entry.entry bcRepository bc(result1) check
set bcChoice1 repository ;# important to enable button 2.2 in UpdateMenu
EnableEntry $w.main.bc.rep.h2.entry bcRepository bc(result1) keyRepositoryList
SetIndicator bc $w.main.bc
if $bcSearch {
	SetBackgroundEntry $w.main.bc.rep.h2.entry.entry bcRepository bc(result1)
} else {
#	PerformCheck $w.main.bc.rep.h2.entry.entry bcRepository bc(result1)
}

PutInternetAddress	;# put the internet address in title

if $installInitialCollection {
# UNPOST THE LOCAL COLLECTION
	set message {URLib initial collection installation is not finished and Apache is not running yet}	;# added by GJFB in 2020-05-28 to skip index updating at unpost
	Store message ../auxdoc/messageForPost	;# added by GJFB in 2020-05-28
	exec $tclPath post -x
	file delete ../auxdoc/messageForPost	;# added by GJFB in 2020-05-28
# UNPOST THE LOCAL COLLECTION - end
# POST THE LOCAL COLLECTION
#	set message [PostLocalCollection]	;# now will run with installInitialCollection == 0 and InformURLibSystem; returns the messageForStart
	set message [PostLocalCollection -c]	;# added by GJFB in 2020-06-02 to make the cgi script - now will run with installInitialCollection == 0 and InformURLibSystem; returns the messageForStart
# POST THE LOCAL COLLECTION - end

while {[catch {Execute $serverAddressWithIP [list TestExecute x] 0}]} {	;# added by GJFB in 2020-05-29 for waiting the first server response
	set y 0; after 100 {set y 1}; vwait y
}

Set startApplicationInUse 1	;# could be anything - added by GJFB in 2020-05-29 - the initial value 1 of startApplicationInUse was lost after doing unpost/post and must be Set again after the first server response
	
	if ![regexp {URLib local collection posted} $message] {
# not posted
		if [regexp {access not completed} $message] {
			foreach {serverName urlibPort} [ReturnCommunicationAddress $serverAddress] {break}
			Dialog OK disabled -1 Start $message $serverName $urlibPort
		} else {
			Dialog OK disabled -1 Start $message
		}
		LogInsert [list [list Insert $log insert {new line}]] 1 0
		LogInsert [list [list Insert $log end {URLib local collection not posted}]] 0 0
		LogInsert [list [list Insert $log insert {new line}]] 0 1
		if {[info exists w] && [winfo exist $w]} {wm withdraw $w}
		exit
	}

	LogInsert [list [list Insert $log insert {new line}]] 1 0
	LogInsert [list [list Insert $log end {initial collection installed successfully}]] 0 0
	LogInsert [list [list Insert $log insert {new line}]] 0 1
	set installInitialCollection 0	;# used in Cancel and OK
}

$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)
EnableButtons
