# Copyright for the Uniform Repository Service (c) 1995 - 2022,
# by Gerald Banon. All rights reserved.
# Version 2.1
# download.tcl
# creates a zip file in the download directory

proc Download {} {
if [catch {
	global env
	global cgi	;# used by ResolveIBI
	global homePath	;# used in FindLanguage
	global loBiMiRep	;# used in MultipleSubmit (called in FindSiteContainingTheOriginal2)
	global loCoInRep	;# used in FormatSiteList called by FindURLPropertyList called by ReturnURLPropertyList called by ReturnURLPropertyList2 called by ResolveIBI
	global URLibServiceRepository
	global localSite	;# used by ResolveIBI in "error $output"
	global serverAddress	;# used by FindURLPropertyList

if 1 {
	puts {Content-Type: text/html}
	puts {}
}
	set col ../../../../..
	set URLibServiceRepository $env(URLIB_SERVICE_REP)
	source ../$col/$URLibServiceRepository/doc/utilities1.tcl
	source ../$col/$URLibServiceRepository/doc/cgi/mirrorfind-.tcl

# homePath (used in FindLanguage)
	set homePath $env(DOCUMENT_ROOT)

	if [info exists env(QUERY_STRING)] {
		foreach {name value} [split $env(QUERY_STRING) &=] {
			set cgi([DecodeURL $name]) [DecodeURL $value]
		}
	}
# loCoInRep
	set loCoInRep $env(LOCOINREP)
# loBiMiRep
	set loBiMiRep $env(LOBIMIREP)	;# used in MultipleSubmit (called in FindSiteContainingTheOriginal2)

#	if ![info exists cgi(mirror)] {set cgi(mirror) $env(LOBIMIREP)}
	ConditionalSet requiredMirror cgi(requiredmirror) $env(LOBIMIREP)	;# used by ReturnURLPropertyList and in Reference

	set pathInfo [file split $env(PATH_INFO)]
# currentRep
	regsub -all { } [lrange $pathInfo 1 4] {/} currentRep

# Find the language and the language repository
# use the same languages as used for the local bibliographic mirror
	foreach {language languageRep1 languageRep2} [FindLanguage $env(LOBIMIREP)] {break}
# Find the language and the language repository - end

# localSite
	set localSite $env(SERVER_NAME):$env(SERVER_PORT)
# serverAddress
	set serverAddress [list $env(SERVER_NAME) $env(URLIB_PORT)]
	
	source ../$col/$languageRep2/doc/mirror/${language}Download.tcl
	
# frameName
if 0 {
# commented by GJFB in 202-06-20
# http://gjfb:1905/download.cgi/dpi.inpe.br/banon-pc2@1905/2006/03.22.15.15/
#                                                                          ^
#                                                                     was required
	if [regexp {/$} $env(PATH_INFO)] {
		set frameName ""
	} else {
		set frameName [lindex $pathInfo end]
	}
} else {
# added by GJFB in 202-06-20
# http://gjfb:1905/download.cgi/dpi.inpe.br/banon-pc2@1905/2006/03.22.15.15
# last / is no more required
		set frameName [lindex $pathInfo end]
}	
# puts $frameName	
	switch -exact -- $frameName {
#	switch -regexp -- $frameName #
		Reference {
#			source ../$col/$languageRep2/doc/mirror/${language}Download.tcl
## bgColor
#			set bgColor [GetBgColor $languageRep1 $language]
			set localURLibClientSocketId [StartCommunication $env(SERVER_NAME) $env(URLIB_PORT)]
# metadataRep
			set metadataRep $cgi(metadatarep)
			
			set referenceType [Submit $localURLibClientSocketId \
				[list ReturnType metadataArray $metadataRep-0] 0]	;# not async
			set title [Submit $localURLibClientSocketId \
				[list GetFieldValue $metadataRep-0 title] 0]	;# not async
# puts --$title--
			set authorList [Submit $localURLibClientSocketId \
				[list GetAuthor $metadataRep-0] 0]	;# not async
			set year [Submit $localURLibClientSocketId \
				[list GetFieldValue $metadataRep-0 year] 0]	;# not async
# puts --$authorList--	;# may contain an error message
			set author [FormatAuthorList $authorList]
			set author "$author :$year:"
			close $localURLibClientSocketId
			set output [subst [set ${languageRep2}::reference]]
		}
		Instructions {
#			source ../$col/$languageRep2/doc/mirror/${language}Download.tcl
			set output [subst [set ${languageRep2}::instructions]]
		}
		Buttons {
#			source ../$col/$languageRep2/doc/mirror/${language}Download.tcl
## bgColor
#			set bgColor [GetBgColor $languageRep1 $language]
# downloadSize
			set downloadSize [ComputeFileSize ../$col/$currentRep/download/doc.zip]
			if {$downloadSize == 0} {
				global "${languageRep2}::<FONT SIZE=-1>No download file available</FONT>"
				set downloadWarning "\${<FONT SIZE=-1>No download file available</FONT>}"
			} elseif {$downloadSize == 1} {
				global "${languageRep2}::Kbyte"
#				set downloadSize "$downloadSize $Kbyte"
				global "${languageRep2}::<FONT SIZE=-1>(download file size: </FONT><TT>1 \$Kbyte</TT><FONT SIZE=-1>)</FONT>"
				set downloadWarning "\${<FONT SIZE=-1>(download file size: </FONT><TT>1 \$Kbyte</TT><FONT SIZE=-1>)</FONT>}"
			} else {
				global "${languageRep2}::Kbytes"
#				set downloadSize "$downloadSize $Kbytes"
				global "${languageRep2}::<FONT SIZE=-1>(download file size: </FONT><TT>\$downloadSize \$Kbytes</TT><FONT SIZE=-1>)</FONT>"
				set downloadWarning "\${<FONT SIZE=-1>(download file size: </FONT><TT>\$downloadSize \$Kbytes</TT><FONT SIZE=-1>)</FONT>}"
			}
#			set output [subst [set ${languageRep2}::buttons]]
#			set output [subst [subst [set ${languageRep2}::buttons]]]
			set output [subst [subst [subst [set ${languageRep2}::buttons]]]]
		}
		default {
## find the metadata of currentRep in the appropriate language
#			set parsedIBIURL [list parsedibiurl.ibi $currentRep parsedibiurl.verblist {GetMetadata GetAppropriateSimilar} parsedibiurl.language $cgi(languagebutton)]
# find the metadata of currentRep in the more appropriate language
#			set parsedIBIURL [list parsedibiurl.ibi $currentRep parsedibiurl.verblist {GetMetadata GetAppropriateSimilar}]
			set parsedIBIURL [list parsedibiurl.ibi $currentRep parsedibiurl.verblist {GetMetadata GetTranslation}]
# puts $parsedIBIURL
			set urlPropertyList2 [ResolveIBI $parsedIBIURL $language 1]
			array set urlPropertyArray $urlPropertyList2
#			set metadataRep $urlPropertyArray(ibi)
			array set ibiArray $urlPropertyArray(ibi)
			set metadataRep $ibiArray(rep)

# puts --$metadataRep--			
			global "${languageRep2}::Download Instructions"
			set localURLibClientSocketId [StartCommunication $env(SERVER_NAME) $env(URLIB_PORT)]

			set versionState [Submit $localURLibClientSocketId [list ComputeVersionState $currentRep {} 1] 0]	;# not async - added by GJFB in 2018-01-02 to avoid creating a doc.zip of a modified document
# puts --$versionState--	;# may contain an error message
# => {Registered Original} {banon-pc3 800} http://banon-pc3/rep-/dpi.inpe.br/banon/1999/12.15.21.29
			foreach {versionState} $versionState {break}
# puts $versionState
			array set stateTable { 
				{Registered Original}				{Official}
				{Modified Original}					{Modified}
				{Copy of the Registered Original}	{Official}
				{Copy of an Original}				{Copied}
				{Modified Copy of an Original}		{Modified}
				{Unchecked}							{Unchecked}
			}
if 0 {
# commented by GJFB in 2021-02-20
			if {![string equal {Modified} $stateTable($versionState)] && ![file exists $env(DOCUMENT_ROOT)/col/$currentRep/download/doc.zip]} {
				regsub {@.*$} $env(SERVER_ADMIN) {} administratorUserName
				Submit $localURLibClientSocketId [list MakeDownloadFile $currentRep 0 0 0 $administratorUserName] 0	;# not async
			}
} else {
# added by GJFB in 2021-02-20 - an existing doc.zip might be out-of-date
			if ![string equal {Modified} $stateTable($versionState)] {
# administratorUserName is the name of the advanced user who is creating the version stamp when making doc.zip
				regsub {@.*$} $env(SERVER_ADMIN) {} administratorUserName
				if [file exists $env(DOCUMENT_ROOT)/col/$currentRep/download/doc.zip] {
# doc.zip exists
					set seconds [file mtime $env(DOCUMENT_ROOT)/col/$currentRep/download/doc.zip]
					set fileTime [clock format $seconds -format %Y:%m.%d.%H.%M.%S -gmt 1]
					SetFieldValue $serverAddress $metadataRep-0 {metadatalastupdate}
					if {[string compare $fileTime $metadatalastupdate] == -1} {
# fileTime < metadatalastupdate - doc.zip out-of-date
#						Submit $localURLibClientSocketId [list MakeDownloadFile $currentRep 0 0 0 $administratorUserName] 0	;# not async - commented by GJFB in 2022-01-30
						Submit $localURLibClientSocketId [list MakeDownloadFile $currentRep 1 0 0 $administratorUserName] 0	;# not async - added by GJFB in 2022-01-30 to include the source directory - useful to preserve the source directory when turning a copy a matriz after an importation
					}
				} else {
# doc.zip doesn't exist
#					Submit $localURLibClientSocketId [list MakeDownloadFile $currentRep 0 0 0 $administratorUserName] 0	;# not async - commented by GJFB in 2022-01-30
					Submit $localURLibClientSocketId [list MakeDownloadFile $currentRep 1 0 0 $administratorUserName] 0	;# not async - added by GJFB in 2022-01-30 to include the source directory - useful to preserve the source directory when turning a copy a matriz after an importation
				}
			}
}			
#			set versionState [Submit $localURLibClientSocketId \
#				[list ComputeVersionState $currentRep $env(LOBIMIREP)] 0]	;# not async
			close $localURLibClientSocketId
#			foreach {state officialSite imageURL} $versionState {break}
# copyrightURL
#			set officialSite [FindSiteContainingTheOriginal2 $currentRep]	;# with ip
			set officialSite [FindSiteContainingTheOriginal2 $currentRep 0]	;# without ip - added by GJFB in 2014-06-18 to solve the case of virtual host
#			if {[string compare $state Official] != 0} #
			if [string equal {} $officialSite] {
				set copyrightURL http://$localSite/copyright.cgi/$currentRep
			} else {
				set copyrightURL http://[ReturnHTTPHost $officialSite]/copyright.cgi/$currentRep
			}
if 0 {
# commented by GJFB in 202-06-20
			set output "
<HTML>
<HEAD>
<TITLE>${Download Instructions}</TITLE>
</HEAD>
<FRAMESET ROWS=\"170,*,50\" BORDER=0 FRAMEBORDER=no>
	<FRAME SRC=\"Reference?metadatarep=$metadataRep&languagebutton=$language&requiredmirror=$requiredMirror\" MARGINWIDTH=0 MARGINHEIGHT=0 SCROLLING=AUTO>
	<FRAMESET COLS=\"52%,600,48%\" BORDER=1 FRAMEBORDER=no>
		<FRAME SRC=\"http://$localSite/col/dpi.inpe.br/banon/2000/01.23.20.24/doc/emptyFrame2.html\" SCROLLING=NO>
		<FRAMESET ROWS=\"*,16,*\" BORDER=0 FRAMEBORDER=no>
			<FRAME SRC=\"Instructions?languagebutton=$language\" MARGINWIDTH=15 MARGINHEIGHT=15>
			<FRAME SRC=\"http://$localSite/col/dpi.inpe.br/banon/2000/01.23.20.24/doc/emptyFrame2.html\" SCROLLING=NO>
			<FRAME SRC=\"$copyrightURL\" MARGINWIDTH=15 MARGINHEIGHT=15>
		</FRAMESET>
		<FRAME SRC=\"http://$localSite/col/dpi.inpe.br/banon/2000/01.23.20.24/doc/emptyFrame2.html\" SCROLLING=NO>
	</FRAMESET>
	<FRAME SRC=\"Buttons?languagebutton=$language\" MARGINWIDTH=0 MARGINHEIGHT=8 SCROLLING=NO>
</FRAMESET>
<NOFRAMES>
Your browser cannot display frames.
</NOFRAMES>
</HTML>
"
} else {
# added by GJFB in 202-06-20
			set output "
<HTML>
<HEAD>
<TITLE>${Download Instructions}</TITLE>
</HEAD>
<FRAMESET ROWS=\"170,*,60\" BORDER=0 FRAMEBORDER=no>
	<FRAME SRC=\"http://$localSite/download.cgi/$currentRep/Reference?metadatarep=$metadataRep&languagebutton=$language&requiredmirror=$requiredMirror\" MARGINWIDTH=0 MARGINHEIGHT=0 SCROLLING=AUTO>
	<FRAMESET COLS=\"52%,600,48%\" BORDER=1 FRAMEBORDER=no>
		<FRAME SRC=\"http://$localSite/col/dpi.inpe.br/banon/2000/01.23.20.24/doc/emptyFrame2.html\" SCROLLING=NO>
		<FRAMESET ROWS=\"*,16,*\" BORDER=0 FRAMEBORDER=no>
			<FRAME SRC=\"http://$localSite/download.cgi/$currentRep/Instructions?languagebutton=$language\" MARGINWIDTH=15 MARGINHEIGHT=15>
			<FRAME SRC=\"http://$localSite/col/dpi.inpe.br/banon/2000/01.23.20.24/doc/emptyFrame2.html\" SCROLLING=NO>
			<FRAME SRC=\"$copyrightURL\" MARGINWIDTH=15 MARGINHEIGHT=15>
		</FRAMESET>
		<FRAME SRC=\"http://$localSite/col/dpi.inpe.br/banon/2000/01.23.20.24/doc/emptyFrame2.html\" SCROLLING=NO>
	</FRAMESET>
	<FRAME SRC=\"http://$localSite/download.cgi/$currentRep/Buttons?languagebutton=$language\" MARGINWIDTH=0 MARGINHEIGHT=8 SCROLLING=auto>
</FRAMESET>
<NOFRAMES>
Your browser cannot display frames.
</NOFRAMES>
</HTML>
"
}
		}
	}
	puts $output
} m] {
#	puts {Content-Type: text/html}
#	puts {}
	puts $m
	if 0 {global errorInfo; puts $errorInfo}
}
}
