#!/bin/csh -f
# \
if ("$1" == "--wish-cmd") then
# \
  set wish = "$2"
# \
else
# \
  set wish = "`/bin/sh -ce 'which wish8.0'`"
# \
  if (! -e "$wish") then
# \
    set wish = "`/bin/sh -ce 'which wish4.2'`"
# \
    if (! -e "$wish") then
# \
      echo "Cannot find wish8.0 or wish4.2.  Is Tcl/Tk installed?"
# \
      echo "If wish8.0 or wish4.2 is installed in a strange place, re-run"
# \
      echo "the installer with the '--wish-cmd' option."
# \
      exit 1
# \
    endif
# \
  endif
# \
endif
# \
exec $wish -f $0 --wish-cmd $wish $*
# 

global Wish
set Wish "/usr/local/bin/wish8.0"
global Prefix
set Prefix "/usr/local"
global InstallerDir
set InstallerDir "[file dirname [info script]]"
if {[string compare "$InstallerDir" {.}] == 0} {
  set InstallerDir [pwd]
}

puts stderr "*** InstallerDir = $InstallerDir"

global TempDir
global env

if {[catch "set env(TMPDIR)" TempDir]} {
  set TempDir "/usr/tmp"
}

global argc
global argv
set tmpArgv ""
for {set counter 0} {$counter < $argc} {incr counter 1} {
  case [string tolower [lindex $argv $counter]] in {
   {--wish-cmd} {
     incr counter 1
     set Wish [lindex $argv $counter]
   }
   {--prefix} {
     incr counter 1
     set Prefix [lindex $argv $counter]
   }
 }
}

catch "file delete -force [file join $TempDir ALib]"
catch "file delete -force [file join $TempDir Lib]"
catch "file delete -force [file join $TempDir Doc]"
catch "file delete -force [file join $TempDir Src]"

image create photo install -file [file join $InstallerDir install.gif]
image create photo banner -file [file join $InstallerDir DeepwoodsBanner.gif]
image create photo exitim -file [file join $InstallerDir exit.gif]
image create photo blue_prev -file [file join $InstallerDir blue_prev.gif]
image create photo help -file [file join $InstallerDir help.gif]
image create photo gnu-head-sm -file [file join $InstallerDir gnu-head-sm.gif]
image create photo front -file [file join $InstallerDir ffront.gif]


global RemoveFilesP
set RemoveFilesP 0
global CommonLib ArchLib ArchBin CommonDoc CommonSrc

set CommonLib {}
set ArchLib {}
set ArchBin {}
set CommonDoc {}
set CommonSrc {}

option add *__tk__messagebox.msg.wrapLength 5i interactive

proc CleanupExit {} {
  global RemoveFilesP
  global CommonLib ArchLib ArchBin CommonDoc CommonSrc
  global TempDir

  if {$RemoveFilesP} {
    catch "file delete -force $ArchLib"
    catch "file delete -force $ArchBin"
    catch "file delete -force $CommonLib"
    catch "file delete -force $CommonDoc"
    catch "file delete -force $CommonSrc"
  }
  
  catch "file delete -force [file join $TempDir ALib]"
  catch "file delete -force [file join $TempDir Lib]"
  catch "file delete -force [file join $TempDir Doc]"
  catch "file delete -force [file join $TempDir Src]"
  tk_messageBox -icon error -message {Installation Aborted!} -default ok
  exit
}

proc Minimize {} {
  if {[winfo exists .icon]} {
    wm deiconify .icon
  } else {
    global ScreenWidth
    global ScreenHeight
    toplevel .icon
    wm transient .icon .
    wm protocol .icon WM_DELETE_WINDOW {Restore}
    label .icon.c -image install
    pack .icon.c -side left
    button .icon.b -text {Home Librarian 2.0 Installer} -command {Restore}
    pack .icon.b -side right -expand 1 -fill y
    wm withdraw .icon
    update idle
    set x [expr $ScreenWidth / 2 - [winfo reqwidth .icon] / 2]
    set y [expr $ScreenHeight / 2 - [winfo reqheight .icon] / 2]
    wm geom .icon +$x+$y
    wm deiconify .icon
  }
  wm withdraw .
}

proc Restore {} {
  wm deiconify .
  wm withdraw .icon
}

proc InstallerHelp {} {
  tk_messageBox -icon warning -message {No Help yet.} -default ok
}

wm withdraw .
global ScreenWidth
global ScreenHeight
set ScreenWidth [winfo screenwidth .]
set ScreenHeight [winfo screenheight .]

proc MainScreen {} {
  global ScreenWidth
  global ScreenHeight
  wm overrideredirect . 1
  canvas .screen -width [expr $ScreenWidth - 8] -height [expr $ScreenHeight - 8] -relief ridge -borderwidth 4 \
		-highlightthickness 0 -background #00008b
  pack .screen
  set ScreenWidth_2 [expr $ScreenWidth / 2]
  set off1 [expr $ScreenHeight * .1]
  .screen create image $ScreenWidth_2 $off1 -anchor n -image banner
  if {[catch [list \
  .screen create text  $ScreenWidth_2 $off1 -anchor n -text {Home Librarian 2.0} \
 				 -fill red \
 -font {-adobe-new century schoolbook-bold-r-normal-*-*-400-*-*-*-*-*-*}]]} {
  .screen create text  $ScreenWidth_2 $off1 -anchor n -text {Home Librarian 2.0} \
 				 -fill red \
 -font {-adobe-new century schoolbook-bold-r-normal-*-*-240-*-*-*-*-*-*}
  }
  button .screen.exit -image exitim -command {CleanupExit}
  update idle
  set etop [expr $ScreenHeight - ([winfo reqheight .screen.exit] + 10)]
  set left [expr $ScreenWidth - ([winfo reqwidth .screen.exit] + 20)]
  .screen create window $left $etop \
	-window .screen.exit -anchor nw
  frame .screen.min -borderwidth 0 -background #00008b
  label .screen.min.l -image blue_prev
  pack .screen.min.l -side top
  button .screen.min.b -text {Min} -command {Minimize} -padx 0 -pady 0
  pack .screen.min.b -side bottom
  update idle
  set mtop [expr $etop - ([winfo reqheight .screen.min] + 10)]
  .screen create window $left $mtop \
	-window .screen.min -anchor nw
  button .screen.help -image help -command {InstallerHelp}
  set htop [expr $mtop - ([winfo reqheight .screen.help] + 10)]
  .screen create window $left $htop \
	-window .screen.help -anchor nw
  wm deiconify .
}

global tcl_version
if {$tcl_version < 7.6} {
  puts "Opps this version of tcl ($tcl_version) is too old!"
  exit 99
}


MainScreen

proc FigureSimpleOsVM {} {
  global SimpleOsVM
  global tcl_platform
  switch -glob $tcl_platform(os) {
    IRIX* {set SimpleOsVM "Irix-[lindex [split $tcl_platform(osVersion) '.'] 0]"}
    SunOS {
	switch -glob $tcl_platform(machine) {
	  sun4* {set SimpleOsVM "SunOS-Sparc-[lindex [split $tcl_platform(osVersion) '.'] 0]"}
	  sun3* {set SimpleOsVM "SunOS-68K-[lindex [split $tcl_platform(osVersion) '.'] 0]"}
	  default {set SimpleOsVM "SunOS-x86-[lindex [split $tcl_platform(osVersion) '.'] 0]"}
	}
    }
    Linux {
	switch -glob $tcl_platform(machine) {
	  i?86 {set SimpleOsVM "Linux-x86-[lindex [split $tcl_platform(osVersion) '.'] 0]"}
	  alpha {set SimpleOsVM "Linux-alpha-[lindex [split $tcl_platform(osVersion) '.'] 0]"}
	}
    }
    OSF? {set SimpleOsVM "OSF-alpha-[lindex [split $tcl_platform(osVersion) '.'] 0]"}
    default {set SimpleOsVM "$tcl_platform(os)-$tcl_platform(machine)-[lindex [split $tcl_platform(osVersion) '.'] 0]"}
 }
}
    
FigureSimpleOsVM

global SkipArchLib
global ArchLibArchive
global tcl_version

set ArchLibArchive "$SimpleOsVM-Tcl$tcl_version.tar.gz"

global tk_version
global tcl_platform
global SimpleOsVM
set Platcode "$SimpleOsVM"
set tcltkver "Tcl$tcl_version/Tk$tk_version"
option add *startup.msg.wrapLength 5i interactive
if {[tk_dialog .startup {Install startup} \
	"This installer will install Home Librarian 2.0\nOn your $Platcode with $tcltkver" \
	info 0 {Don't Install} {Install}] == 0} {
  CleanupExit
}

option add *welcome.msg.wrapLength 5i interactive
tk_dialog .welcome {Welcome message} \
"      Home Librarian 2.0 for UNIX\n\
Copyright (c) 1991-1998 Deepwoods Software\n\
     51 Locke Hill Road\n\
     Wendell, MA 01379\n\
     support@deepsoft.com" info 0 {Continue}

if {![file exists $ArchLibArchive]} {
  tk_dialog .warning {No bins for this archive!} \
	"There are no binaries for $SimpleOsVM-Tcl$tcl_version.\n\
None will be installed.  You will need to configure and compile from sources." \
	warning 0 Continue
  set SkipArchLib 1
} else {
  set SkipArchLib 0
}

proc PutUpProgressBar {title} {

# .progressBar
# The above line makes pasting MUCH easier for me.
# It contains the pathname of the cutted widget.
# Tcl version: 7.6 (Tcl/Tk/XF)
# Tk version: 4.2
# XF version: 4.0
#

  # build widget .progressBar
  if {"[info procs XFEdit]" != ""} {
    catch "XFDestroy .progressBar"
  } {
    catch "destroy .progressBar"
  }
  toplevel .progressBar 

  # Window manager configurations
  wm positionfrom .progressBar ""
  wm sizefrom .progressBar ""
  wm maxsize .progressBar 1009 738
  wm minsize .progressBar 1 1
  wm protocol .progressBar WM_DELETE_WINDOW {CleanupExit}
  wm title .progressBar "$title"
  wm transient .progressBar .

  # build widget .progressBar.top
  frame .progressBar.top \
    -borderwidth {2}

  # build widget .progressBar.top.label4
  label .progressBar.top.label4 \
    -bitmap {questhead}

  # build widget .progressBar.top.label5
  label .progressBar.top.label5 \
    -text "$title"

  # build widget .progressBar.progress
  frame .progressBar.progress \
    -borderwidth {2} \
    -relief {ridge}

  # build widget .progressBar.progress.what
  label .progressBar.progress.what \
    -background {white} -justify left

  # build widget .progressBar.progress.from
  frame .progressBar.progress.from \
    -borderwidth {2}

  # build widget .progressBar.progress.from.label6
  label .progressBar.progress.from.label6 \
    -text {From:}

  # build widget .progressBar.progress.from.value
  label .progressBar.progress.from.value \
    -background {white} \
    -relief {sunken} -justify left

  # build widget .progressBar.progress.to
  frame .progressBar.progress.to \
    -borderwidth {2}

  # build widget .progressBar.progress.to.label6
  label .progressBar.progress.to.label6 \
    -text {To:}

  # build widget .progressBar.progress.to.value
  label .progressBar.progress.to.value \
    -background {white} \
    -relief {sunken} -justify left

  # build widget .progressBar.progress.bar
  frame .progressBar.progress.bar \
    -borderwidth {2}

  # build widget .progressBar.progress.bar.bar
  canvas .progressBar.progress.bar.bar \
    -background {white} \
    -borderwidth {2} \
    -height {20} \
    -relief {sunken} \
    -width {400}

  # build widget .progressBar.button9
  button .progressBar.button9 \
    -command {CleanupExit} \
    -padx {9} \
    -pady {3} \
    -text {Abort}

  # pack master .progressBar.top
  pack configure .progressBar.top.label4 \
    -fill x \
    -side left
  pack configure .progressBar.top.label5 \
    -expand 1 \
    -fill x \
    -side right

  # pack master .progressBar.progress
  pack configure .progressBar.progress.what \
    -expand 1 \
    -fill x
  pack configure .progressBar.progress.from \
    -fill x
  pack configure .progressBar.progress.to \
    -fill x
  pack configure .progressBar.progress.bar \
    -fill x

  # pack master .progressBar.progress.from
  pack configure .progressBar.progress.from.label6 \
    -fill x \
    -side left
  pack configure .progressBar.progress.from.value \
    -expand 1 \
    -fill x \
    -side right

  # pack master .progressBar.progress.to
  pack configure .progressBar.progress.to.label6 \
    -fill x \
    -side left
  pack configure .progressBar.progress.to.value \
    -expand 1 \
    -fill x \
    -side right

  # pack master .progressBar.progress.bar
  pack configure .progressBar.progress.bar.bar \
    -padx 20 \
    -pady 20

  # pack master .progressBar
  pack configure .progressBar.top \
    -fill x
  pack configure .progressBar.progress \
    -expand 1 \
    -fill both
  pack configure .progressBar.button9

  # build canvas items .progressBar.progress.bar.bar
  set xfTmpTag [.progressBar.progress.bar.bar create rectangle 0.0 0.0 0.0 0.0]
  .progressBar.progress.bar.bar itemconfigure $xfTmpTag \
    -fill {blue} \
    -outline {} \
    -tags {theBar}

  wm withdraw .progressBar
  update idle
  global ScreenWidth ScreenHeight

  set x [expr $ScreenWidth / 2 - [winfo reqwidth .progressBar] / 2]
  set y [expr $ScreenHeight / 2 - [winfo reqheight .progressBar] / 2]
  wm geom .progressBar +$x+$y
  wm deiconify .progressBar


# end of widget tree

}


proc UpdatePBar {what from to percentdone} {
  .progressBar.progress.what config -text "$what"
  .progressBar.progress.from.value config -text "$from"
  .progressBar.progress.to.value config -text "$to"
  set x [expr $percentdone * 400.0 + 2]
  .progressBar.progress.bar.bar coords theBar 2 2 $x 22
  update
}

proc RemoveProgressBar {} {
  .progressBar.button9 config \
	-text {Continue} \
	-command {catch "destroy .progressBar"}
  wm protocol .progressBar WM_DELETE_WINDOW {catch "destroy .progressBar"}

  tkwait window .progressBar.button9
}

PutUpProgressBar {Uncompressing...}

if {$SkipArchLib} {
  set archives {{ALib {}} {Doc Doc.tar.gz} {Lib Lib.tar.gz} {Src Source.tar.gz}}
} else {
  set archives [list \
	[list ALib $ArchLibArchive] \
	{Doc Doc.tar.gz} {Lib Lib.tar.gz} {Src Source.tar.gz}]
}

set archive2s {}
set total 0
option add *error.msg.wrapLength 6i interactive

foreach aa $archives {
  set a [lindex $aa 1]
  if {[string length  "$a"] == 0} {
    lappend archive2s [list [lindex $aa 0] $a 0]
    continue
  } elseif {[catch [list exec gzip -l [file join $InstallerDir $a]] gzinfo]} {
    RemoveProgressBar
    tk_dialog .error {gzip error} \
	"Error from gzip -l $a: $gzinfo" \
	error 0 {Continue}
    CleanupExit
  }
  set lastline [lindex [split "$gzinfo" "\n"] end]
  set lastline [eval concat $lastline]
  set as [expr ([lindex $lastline 1] + 1023) / 1024]
  lappend archive2s [list [lindex $aa 0] $a $as]
  set total [expr $total + $as]
}

set csize 0

foreach aa $archive2s {
  set dir [file join $TempDir [lindex $aa 0]]
  if {[catch [list file mkdir $dir] error]} {
    RemoveProgressBar
    tk_dialog .error {mkdir error} \
       "Error creating temp directory $dir: $error" \
	error 0 {Continue}
    CleanupExit
  }
  set arch [lindex $aa 1]
  set asize [lindex $aa 2]
  if {[string length "$arch"] == 0} {continue}
  cd $dir
  if {[catch "exec gunzip -c [file join $InstallerDir $arch] | tar xf -" error]} {
    if {[string compare "$error" {child killed: write on pipe with no readers}] != 0} {
      RemoveProgressBar
      tk_dialog .error {Uncompressing error} \
  	"Error unpacking $arch: $error" error 0 {Continue}
      CleanupExit
    }
  }
  cd $InstallerDir
  set csize [expr $csize + $asize]
  UpdatePBar {Uncompressing Files} "$arch" "$dir" [expr double($csize) / $total]
}

RemoveProgressBar

proc GetInfo {} {

  global Continue
  set Continue -1

# .getInfo
# The above line makes pasting MUCH easier for me.
# It contains the pathname of the cutted widget.
# Tcl version: 7.6 (Tcl/Tk/XF)
# Tk version: 4.2
# XF version: 4.0
#

  # build widget .getInfo
  if {"[info procs XFEdit]" != ""} {
    catch "XFDestroy .getInfo"
  } {
    catch "destroy .getInfo"
  }
  toplevel .getInfo 

  bind .getInfo <Return> {tkButtonInvoke .getInfo.button3}

  # Window manager configurations
  wm maxsize .getInfo 1009 738
  wm minsize .getInfo 1 1
  wm protocol .getInfo WM_DELETE_WINDOW {global Continue;set Continue 0}
  wm title .getInfo {Get User Info}
  wm transient .getInfo .

  # build widget .getInfo.top
  frame .getInfo.top \
    -borderwidth {2}

  # build widget .getInfo.top.label4
  label .getInfo.top.label4 \
    -bitmap {questhead}
 
  # build widget .getInfo.top.label5
  label .getInfo.top.label5 \
    -text {Enter user information}

  # build widget .getInfo.values
  frame .getInfo.values \
    -borderwidth {2} \
    -relief {ridge}

  # build widget .getInfo.values.user
  frame .getInfo.values.user \
    -borderwidth {2}

  # build widget .getInfo.values.user.label9
  label .getInfo.values.user.label9 \
    -text {Name:}

  # build widget .getInfo.values.user.value
  entry .getInfo.values.user.value

  # build widget .getInfo.values.comp
  frame .getInfo.values.comp \
    -borderwidth {2}

  # build widget .getInfo.values.comp.label9
  label .getInfo.values.comp.label9 \
    -text {Company:}

  # build widget .getInfo.values.comp.value
  entry .getInfo.values.comp.value

  # build widget .getInfo.values.serial
  frame .getInfo.values.serial \
    -borderwidth {2}

  # build widget .getInfo.values.serial.label9
  label .getInfo.values.serial.label9 \
    -text {Serial:}

  # build widget .getInfo.values.serial.value
  entry .getInfo.values.serial.value

  # build widget .getInfo.button3
  button .getInfo.button3 \
    -padx {9} \
    -pady {3} \
    -text {Continue} \
    -command {global Continue;set Continue 1}

  # pack master .getInfo.top
  pack configure .getInfo.top.label4 \
    -fill x \
    -side left
  pack configure .getInfo.top.label5 \
    -fill x \
    -side right

  # pack master .getInfo.values
  pack configure .getInfo.values.user \
    -fill x
  pack configure .getInfo.values.comp \
    -fill x
  pack configure .getInfo.values.serial \
    -fill x

  # pack master .getInfo.values.user
  pack configure .getInfo.values.user.label9 \
    -side left
  pack configure .getInfo.values.user.value \
    -expand 1 \
    -fill x \
    -side right

  # pack master .getInfo.values.comp
  pack configure .getInfo.values.comp.label9 \
    -side left
  pack configure .getInfo.values.comp.value \
    -expand 1 \
    -fill x \
    -side right

  # pack master .getInfo.values.serial
  pack configure .getInfo.values.serial.label9 \
    -side left
  pack configure .getInfo.values.serial.value \
    -expand 1 \
    -fill x \
    -side right

  # pack master .getInfo
  pack configure .getInfo.top \
    -fill x
  pack configure .getInfo.values \
    -expand 1 \
    -fill both
  pack configure .getInfo.button3 \
    -expand 1

  .getInfo.values.user.value insert end {}
  .getInfo.values.comp.value insert end {}
  .getInfo.values.serial.value insert end {}


# end of widget tree
  wm withdraw .getInfo
  update idle

  global ScreenWidth ScreenHeight

  set x [expr $ScreenWidth / 2 - [winfo reqwidth .getInfo] / 2]
  set y [expr $ScreenHeight / 2 - [winfo reqheight .getInfo] / 2]
  wm geom .getInfo +$x+$y
  wm deiconify .getInfo

  focus .getInfo.values.user.value

  tkwait variable Continue

  if {$Continue != 1} {CleanupExit}

  global User Company Serial
  set User "[.getInfo.values.user.value get]"
  set Company "[.getInfo.values.comp.value get]"
  set Serial "[.getInfo.values.serial.value get]"
  if {"[info procs XFEdit]" != ""} {
    catch "XFDestroy .getInfo"
  } {
    catch "destroy .getInfo"
  }

}

proc DoReadMe {title bitmap file} {

  if {[catch [list open "$file" r] ifp]} {
    tk_dialog .warning {File error} \
      "Could not open text file $file: $ifp" warning 0 Continue
    return
  }

# .readme
# The above line makes pasting MUCH easier for me.
# It contains the pathname of the cutted widget.
# Tcl version: 7.6 (Tcl/Tk/XF)
# Tk version: 4.2
# XF version: 4.0
#

  # build widget .readme
  if {"[info procs XFEdit]" != ""} {
    catch "XFDestroy .readme"
  } {
    catch "destroy .readme"
  }
  toplevel .readme 

  # Window manager configurations
  wm transient .readme .
  wm positionfrom .readme ""
  wm sizefrom .readme ""
  wm maxsize .readme 1009 738
  wm minsize .readme 1 1
  wm title .readme "$title"

  bind .readme <Return> {tkButtonInvoke .readme.theFrame.bmbut.button14}

  # build widget .readme.top
  frame .readme.top \
    -borderwidth {2}

  # build widget .readme.top.label4
  label .readme.top.label4 \
    -bitmap {questhead}

  # build widget .readme.top.label5
  label .readme.top.label5 \
    -text "$title"

  # build widget .readme.theFrame
  frame .readme.theFrame \
    -borderwidth {2} \
    -relief {ridge}

  # build widget .readme.theFrame.bmbut
  frame .readme.theFrame.bmbut \
    -borderwidth {2}

  # build widget .readme.theFrame.bmbut.label13
  label .readme.theFrame.bmbut.label13 \
    -relief {ridge} -image $bitmap

  # build widget .readme.theFrame.bmbut.button14
  button .readme.theFrame.bmbut.button14 \
    -command {  if {"[info procs XFEdit]" != ""} {
    catch "XFDestroy .readme"
  } {
    catch "destroy .readme"
  }
} \
    -padx {9} \
    -pady {3} \
    -text {Continue}

  # build widget .readme.theFrame.frame
  frame .readme.theFrame.frame \
    -relief {raised}

  # build widget .readme.theFrame.frame.scrollbar1
  scrollbar .readme.theFrame.frame.scrollbar1 \
    -command {.readme.theFrame.frame.text2 yview} \
    -relief {raised}

  # build widget .readme.theFrame.frame.text2
  text .readme.theFrame.frame.text2 \
    -relief {raised} \
    -wrap {word} \
    -yscrollcommand {.readme.theFrame.frame.scrollbar1 set}
  # bindings
  bind .readme.theFrame.frame.text2 <Key> {break}

  # pack master .readme.top
  pack configure .readme.top.label4 \
    -fill x \
    -side left
  pack configure .readme.top.label5 \
    -expand 1 \
    -fill x \
    -side right

  # pack master .readme.theFrame
  pack configure .readme.theFrame.bmbut \
    -expand 1 \
    -fill y \
    -side left
  pack configure .readme.theFrame.frame \
    -expand 1 \
    -fill both \
    -side right

  # pack master .readme.theFrame.bmbut
  pack configure .readme.theFrame.bmbut.label13
  pack configure .readme.theFrame.bmbut.button14 \
    -expand 1

  # pack master .readme.theFrame.frame
  pack configure .readme.theFrame.frame.scrollbar1 \
    -fill y \
    -side right
  pack configure .readme.theFrame.frame.text2 \
    -expand 1 \
    -fill both

  # pack master .readme
  pack configure .readme.top \
    -fill x
  pack configure .readme.theFrame

  .readme.theFrame.frame.text2 insert end "[read $ifp]"
  close $ifp

  wm withdraw .readme
  update idle
  global ScreenWidth ScreenHeight
  set x [expr $ScreenWidth / 2 - [winfo reqwidth .readme] / 2]
  set y [expr $ScreenHeight / 2 - [winfo reqheight .readme] / 2]
  wm geom .readme +$x+$y
  wm deiconify .readme

  tkwait window .readme 


# end of widget tree


}


DoReadMe {General README} front [file join $TempDir Doc/README.1st]
DoReadMe {UNIX README} front [file join $TempDir Doc/README.UNIX]
DoReadMe {GNU Public License} gnu-head-sm [file join $TempDir Doc/COPYING]


global Continue
set Continue -1

while {$Continue < 0} {
  GetInfo
  global User
  if {[string length "$User"] < 4} {
    tk_dialog .error {Name too short} \
	{You must enter a name of 4 or more characters} error 0 Continue
    set Continue -1
  }
}

global CommonLib ArchLib ArchBin CommonDoc CommonSrc Prefix 
global SimpleOsVM tcl_version

set CommonLib "[file join $Prefix {hl20/Lib}]"
set ArchLib "[file join $Prefix hl20/Lib $SimpleOsVM-Tcl$tcl_version]"
set ArchBin "[file join $Prefix hl20/Bin $SimpleOsVM-Tcl$tcl_version]"
set CommonDoc "[file join $Prefix {hl20/Doc}]"
set CommonSrc "[file join $Prefix {hl20/Src}]"

proc Df {dir} {
  while {![file exists $dir]} {
    set dir [file dirname $dir]
  }
  if {[catch [list exec df -k $dir] dfinfo]} {
    if {[catch [list exec df $dir] dfinfo]} {
      return -1
    }
  }
  set lastline [lindex [split "$dfinfo" "\n"] end]
  set lastline [eval concat $lastline]
  return [lindex $lastline 3]
}

proc Fs {dir} {
  while {![file exists $dir]} {
    set dir [file dirname $dir]
  }
  if {[catch [list exec df -k $dir] dfinfo]} {
    if {[catch [list exec df $dir] dfinfo]} {
      return -1
    }
  }
  set lastline [lindex [split "$dfinfo" "\n"] end]
  set lastline [eval concat $lastline]
  return [lindex $lastline end]
}

proc Du {dir} {
  if {[catch [list exec du -k -s $dir] duinfo]} {
    if {[catch [list exec du -s $dir] duinfo]} {
      return 0
    }
  }
  return [lindex [split "$duinfo"] 0]
}


proc GetDirectories {} {
  global Continue
  set Continue -1
  global SimpleOsVM
  global tcl_version
  global TempDir
  global CommonLib ArchLib ArchBin CommonDoc CommonSrc

# .getDirectories
# The above line makes pasting MUCH easier for me.
# It contains the pathname of the cutted widget.
# Tcl version: 7.6 (Tcl/Tk/XF)
# Tk version: 4.2
# XF version: 4.0
#

  # build widget .getDirectories
  if {"[info procs XFEdit]" != ""} {
    catch "XFDestroy .getDirectories"
  } {
    catch "destroy .getDirectories"
  }
  toplevel .getDirectories 

  bind .getDirectories <Return> {tkButtonInvoke .getDirectories.button3}

  # Window manager configurations
  wm maxsize .getDirectories 1009 738
  wm minsize .getDirectories 1 1
  wm protocol .getDirectories WM_DELETE_WINDOW {global Continue;set Continue 0}
  wm title .getDirectories {Get Install Directories}
  wm transient .getDirectories .

  # build widget .getDirectories.top
  frame .getDirectories.top \
    -borderwidth {2}

  # build widget .getDirectories.top.label4
  label .getDirectories.top.label4 \
    -bitmap {questhead}

  # build widget .getDirectories.top.label5
  label .getDirectories.top.label5 \
    -text {Enter Installation directories}

  # build widget .getDirectories.values
  frame .getDirectories.values \
    -borderwidth {2} \
    -relief {ridge}

  # build widget .getDirectories.values.commonLib
  frame .getDirectories.values.commonLib \
    -borderwidth {2}

  # build widget .getDirectories.values.commonLib.label9
  label .getDirectories.values.commonLib.label9 \
    -text {Common Library:}

  # build widget .getDirectories.values.commonLib.value
  entry .getDirectories.values.commonLib.value -width 0
  bind .getDirectories.values.commonLib.value <Return> {UpdateASize commonLib}  
  bind .getDirectories.values.commonLib.value <space> {UpdateASize commonLib}  

  # build widget .getDirectories.values.commonLib.need
  label .getDirectories.values.commonLib.need \
    -text "Need: [Du [file join $TempDir Lib]]Ks"

  # build widget .getDirectories.values.commonLib.avail
  label .getDirectories.values.commonLib.avail \
    -text "[Df $CommonLib]Ks Available"

  # build widget .getDirectories.values.archLib
  frame .getDirectories.values.archLib \
    -borderwidth {2}

  # build widget .getDirectories.values.archLib.label9
  label .getDirectories.values.archLib.label9 \
    -text {Arch. Specific Library:}

  # build widget .getDirectories.values.archLib.value
  entry .getDirectories.values.archLib.value -width 0
  bind .getDirectories.values.archLib.value <Return> {UpdateASize archLib}  
  bind .getDirectories.values.archLib.value <space> {UpdateASize archLib}  

  # build widget .getDirectories.values.archLib.need
  label .getDirectories.values.archLib.need \
    -text "Need: [Du [file join $TempDir ALib]]Ks"

  # build widget .getDirectories.values.archLib.avail
  label .getDirectories.values.archLib.avail \
    -text "[Df $ArchLib]Ks Available"

  # build widget .getDirectories.values.archBin
  frame .getDirectories.values.archBin \
    -borderwidth {2}

  # build widget .getDirectories.values.archBin.label9
  label .getDirectories.values.archBin.label9 \
    -text {Arch. Specific Binaries:}

  # build widget .getDirectories.values.archBin.value
  entry .getDirectories.values.archBin.value -width 0
  bind .getDirectories.values.archBin.value <Return> {UpdateASize archBin}  
  bind .getDirectories.values.archBin.value <space> {UpdateASize archBin}  

  # build widget .getDirectories.values.archBin.need
  label .getDirectories.values.archBin.need \
    -text "Need: 1K"

  # build widget .getDirectories.values.archBin.avail
  label .getDirectories.values.archBin.avail \
    -text "[Df $ArchBin]Ks Available"

  # build widget .getDirectories.values.commonDoc
  frame .getDirectories.values.commonDoc \
    -borderwidth {2}

  # build widget .getDirectories.values.commonDoc.label9
  label .getDirectories.values.commonDoc.label9 \
    -text {Common Documentaion:}

  # build widget .getDirectories.values.commonDoc.value
  entry .getDirectories.values.commonDoc.value -width 0
  bind .getDirectories.values.commonDoc.value <Return> {UpdateASize commonDoc}  
  bind .getDirectories.values.commonDoc.value <space> {UpdateASize commonDoc}  

  # build widget .getDirectories.values.commonDoc.need
  label .getDirectories.values.commonDoc.need \
    -text "Need: [Du [file join $TempDir Doc]]Ks"

  # build widget .getDirectories.values.commonDoc.avail
  label .getDirectories.values.commonDoc.avail \
    -text "[Df $CommonDoc]Ks Available"

  # build widget .getDirectories.values.commonSrc
  frame .getDirectories.values.commonSrc \
    -borderwidth {2}

  # build widget .getDirectories.values.commonSrc.label9
  label .getDirectories.values.commonSrc.label9 \
    -text {Common Source:}

  # build widget .getDirectories.values.commonSrc.value
  entry .getDirectories.values.commonSrc.value -width 0
  bind .getDirectories.values.commonSrc.value <Return> {UpdateASize commonLib}  
  bind .getDirectories.values.commonSrc.value <space> {UpdateASize commonLib}  

  # build widget .getDirectories.values.commonSrc.need
  label .getDirectories.values.commonSrc.need \
    -text "Need: [Du [file join $TempDir Src]]Ks"

  # build widget .getDirectories.values.commonSrc.avail
  label .getDirectories.values.commonSrc.avail \
    -text "[Df $CommonSrc]Ks Available"

  # build widget .getDirectories.button3
  button .getDirectories.button3 \
    -padx {9} \
    -pady {3} \
    -text {Continue} \
    -command {global Continue;set Continue 1}

  # build widget .getDirectories.button4
  button .getDirectories.button4 \
    -padx {9} \
    -pady {3} \
    -text {Update Sizes} \
    -command {RecomputeSizes}

  # pack master .getDirectories.top
  pack configure .getDirectories.top.label4 \
    -fill x \
    -side left
  pack configure .getDirectories.top.label5 \
    -expand 1 \
    -fill x \
    -side right

  # pack master .getDirectories.values
  pack configure .getDirectories.values.commonLib \
    -fill x
  pack configure .getDirectories.values.archLib \
    -fill x
  pack configure .getDirectories.values.archBin \
    -fill x
  pack configure .getDirectories.values.commonDoc \
    -fill x
  pack configure .getDirectories.values.commonSrc \
    -fill x

  # pack master .getDirectories.values.commonLib
  pack configure .getDirectories.values.commonLib.label9 \
    -side left
  pack configure .getDirectories.values.commonLib.value \
    -expand 1 \
    -fill x \
    -side left
  pack configure .getDirectories.values.commonLib.need \
    -side left
  pack configure .getDirectories.values.commonLib.avail \
    -side left


  # pack master .getDirectories.values.archLib
  pack configure .getDirectories.values.archLib.label9 \
    -side left
  pack configure .getDirectories.values.archLib.value \
    -expand 1 \
    -fill x \
    -side left
  pack configure .getDirectories.values.archLib.need \
    -side left
  pack configure .getDirectories.values.archLib.avail \
    -side left

  # pack master .getDirectories.values.archBin
  pack configure .getDirectories.values.archBin.label9 \
    -side left
  pack configure .getDirectories.values.archBin.value \
    -expand 1 \
    -fill x \
    -side left
  pack configure .getDirectories.values.archBin.need \
    -side left
  pack configure .getDirectories.values.archBin.avail \
    -side left

  # pack master .getDirectories.values.commonDoc
  pack configure .getDirectories.values.commonDoc.label9 \
    -side left
  pack configure .getDirectories.values.commonDoc.value \
    -expand 1 \
    -fill x \
    -side left
  pack configure .getDirectories.values.commonDoc.need \
    -side left
  pack configure .getDirectories.values.commonDoc.avail \
    -side left

  # pack master .getDirectories.values.commonSrc
  pack configure .getDirectories.values.commonSrc.label9 \
    -side left
  pack configure .getDirectories.values.commonSrc.value \
    -expand 1 \
    -fill x \
    -side left
  pack configure .getDirectories.values.commonSrc.need \
    -side left
  pack configure .getDirectories.values.commonSrc.avail \
    -side left

  # pack master .getDirectories
  pack configure .getDirectories.top \
    -fill x
  pack configure .getDirectories.values \
    -expand 1 \
    -fill both
  pack configure .getDirectories.button3 \
    -expand 1 -side left
  pack configure .getDirectories.button4 \
    -expand 1 -side right

  .getDirectories.values.commonLib.value insert end "$CommonLib"
  .getDirectories.values.archLib.value insert end "$ArchLib"
  .getDirectories.values.archBin.value insert end "$ArchBin"
  .getDirectories.values.commonDoc.value insert end "$CommonDoc"
  .getDirectories.values.commonSrc.value insert end "$CommonSrc"


# end of widget tree
  wm withdraw .getDirectories
  update idle
  global ScreenWidth ScreenHeight

  set x [expr $ScreenWidth / 2 - [winfo reqwidth .getDirectories] / 2]
  set y [expr $ScreenHeight / 2 - [winfo reqheight .getDirectories] / 2]
  wm geom .getDirectories +$x+$y
  wm deiconify .getDirectories

  focus .getDirectories.values.commonLib.value

  tkwait variable Continue

  if {$Continue != 1} {CleanupExit}

  set CommonLib "[.getDirectories.values.commonLib.value get]"
  set ArchLib "[.getDirectories.values.archLib.value get]"
  set ArchBin "[.getDirectories.values.archBin.value get]"
  set CommonDoc "[.getDirectories.values.commonDoc.value get]"
  set CommonSrc "[.getDirectories.values.commonSrc.value get]"
  
  if {"[info procs XFEdit]" != ""} {
    catch "XFDestroy .getDirectories"
  } {
    catch "destroy .getDirectories"
  }

}

proc RecomputeSizes {} {
  foreach d {commonLib archLib archBin commonDoc commonSrc} {
    UpdateASize $d
  }
}

proc UpdateASize {d} {
  .getDirectories.values.$d.avail config \
		-text "[Df [.getDirectories.values.$d.value get]]Ks Available"
}

proc CheckSpaces {} {
  global TempDir
  global CommonLib ArchLib ArchBin CommonDoc CommonSrc
  set spaces [list \
      [list [Fs $CommonLib] [Du [file join $TempDir Lib]]] \
      [list [Fs $ArchLib] [Du [file join $TempDir ALib]]] \
      [list [Fs $ArchBin] 1] \
      [list [Fs $CommonDoc] [Du [file join $TempDir Doc]]] \
      [list [Fs $CommonSrc] [Du [file join $TempDir Src]]]]
  set index 0
  set len [expr [llength $spaces] - 1]
  while {$index < $len} {
    set this [lindex $spaces $index]
    set next [lindex $spaces [expr $index + 1]]
    if {[string compare "[lindex $this 0]" "[lindex $next 0]"] == 0} {
      set spaces [concat [lrange $spaces 0 [expr $index - 1]] \
      			 [list [list "[lindex $this 0]" [expr [lindex $this 1] + [lindex $next 1]]]] \
			 [lrange $spaces 2 end]]
      incr len -1
    } else {
      incr index
    }
  }
  foreach f $spaces {
    set fs [lindex $f 0]
    set du [lindex $f 1]
    set df [Df $fs]
    if {$df < $du} {
      tk_dialog .error {Space problem} \
	"There is not enough space on $fs, it has $df, needs $du, select another file system." \
	error 0 {Continue}
      return 0
    }
  }
  return 1
}

global Continue
set Continue -1
while {$Continue < 0} {
  GetDirectories
  if {![CheckSpaces]} {
    set Continue -1
    continue
  }
  if {[catch [list file mkdir $CommonLib] error]} {
    option add *error.msg.wrapLength 6i interactive
    tk_dialog .error {mkdir error} \
	"Error creating the Common Library directory, $CommonLib: $error" \
	error 0 {Continue}
    set Continue -1
    continue
  }
  if {[catch [list file mkdir $ArchLib] error]} {
    option add *error.msg.wrapLength 6i interactive
    tk_dialog .error {mkdir error} \
	"Error creating the Arch. Specific Library directory, $ArchLib: $error" \
	error 0 {Continue}
    set Continue -1
    continue
  }
  if {[catch [list file mkdir $ArchBin] error]} {
    option add *error.msg.wrapLength 6i interactive
    tk_dialog .error {mkdir error} \
	"Error creating the Arch. Specific Binaries directory, $ArchBin: $error" \
	error 0 {Continue}
    set Continue -1
    continue
  }
  if {[catch [list file mkdir $CommonDoc] error]} {
    option add *error.msg.wrapLength 6i interactive
    tk_dialog .error {mkdir error} \
	"Error creating the Common Documentation directory, $CommonDoc: $error" \
	error 0 {Continue}
    set Continue -1
    continue
  }
  if {[catch [list file mkdir $CommonSrc] error]} {
    option add *error.msg.wrapLength 6i interactive
    tk_dialog .error {mkdir error} \
	"Error creating the Common Source directory, $CommonSrc: $error" \
	error 0 {Continue}
    set Continue -1
    continue
  }
}


global RemoveFilesP
set RemoveFilesP 1

set totalSize [expr double([Du [file join $TempDir Lib]]+\
			   [Du [file join $TempDir ALib]]+\
			   [Du [file join $TempDir Doc]]+\
			   [Du [file join $TempDir Src]])]
set currentSize 0.0

PutUpProgressBar {Copying files...}

foreach LibFile [glob -nocomplain [file join $TempDir Lib/*]] {
  file copy -force $LibFile $CommonLib/
  set currentSize [expr $currentSize + ([file size $LibFile] / 1024.0)]
  UpdatePBar {Common Lib (Tcl, GIF, and Help) files} $LibFile $CommonLib [expr $currentSize / $totalSize]
}

foreach ALibFile [glob -nocomplain [file join $TempDir ALib/*]] {
  if {[string compare "$ArchLib" "$CommonLib"] == 0 &&
      [string compare [file tail "$ALibFile"] {pkgIndex.tcl}] == 0} {
    if {[catch [list open [file join "$CommonLib" {pkgIndex.tcl}] a] ofp]} {
      tk_dialog .error {Can't append pkgIndex.tcl} \
		"Cannot open [file join "$CommonLib" {pkgIndex.tcl}] for appendinf: $ofp" \
	error 0 Continue
      CleanupExit
    }
    if {[catch [list open $ALibFile r] ifp]} {
      tk_dialog .error {Can't read pkgIndex.tcl} \
	"Cannot open $ALibFile for reading: $ifp" error 0 Continue
      close $ofp
      CleanupExit
    }
    puts $ofp "[read $ifp]"
    close $ofp
    close $ifp
  } else {
    file copy -force $ALibFile $ArchLib/
  }
  set currentSize [expr $currentSize + ([file size $ALibFile] / 1024.0)]
  UpdatePBar {Arch. specific files} $ALibFile $ArchLib [expr $currentSize / $totalSize]
}

foreach SrcFile [glob -nocomplain [file join $TempDir Src/*]] {
  file copy -force $SrcFile $CommonSrc/
  set currentSize [expr $currentSize + ([file size $SrcFile] / 1024.0)]
  UpdatePBar {Source files} $SrcFile $CommonSrc [expr $currentSize / $totalSize]
}
  
foreach DocFile [glob -nocomplain [file join $TempDir Doc/*]] {
  file copy -force $DocFile $CommonDoc/
  set currentSize [expr $currentSize + ([file size $DocFile] / 1024.0)]
  UpdatePBar {Documentation files} $DocFile $CommonDoc [expr $currentSize / $totalSize]
}

RemoveProgressBar  

proc MakeSh {} {
  tk_messageBox -icon info -message {Creating /bin/sh script to run the Home Librarian program} -default ok

  global Wish
  global CommonLib
  global ArchLib
  global ArchBin

  if {[catch [list open [file join "$ArchBin" {HL20}] w] ofp]} {
    tk_dialog .error {Can't create HL20} \
      "Cannot open [file join $ArchBin {HL20}] for writing: $ofp" error 0 Continue
    CleanupExit
  }

  puts $ofp "#!/bin/sh"
  if {[string compare "$CommonLib" "$ArchLib"] == 0} {
    puts $ofp "TCLLIBPATH=\"$CommonLib\""
    puts $ofp "TCL_PKGPATH=\"$CommonLib\""
  } else {
    puts $ofp "TCLLIBPATH=\"$ArchLib $CommonLib\""
    puts $ofp "TCL_PKGPATH=\"$ArchLib $CommonLib\""
  }
  puts $ofp "export TCLLIBPATH"
  puts $ofp "export TCL_PKGPATH"
  puts $ofp "exec $Wish $CommonLib/HL20.tcl"
  close $ofp
  catch [list exec chmod +x [file join "$ArchBin" {HL20}]]

  tk_messageBox -icon info -default ok \
-message "[file join $ArchBin {HL20}] Created.  If $ArchBin is in your PATH, \n\
then you can just type HL20 to run the Home Librarian 2.0 GUI, otherwise you can\n\
create an alias or a symbolic link."

}

proc MakeReg {} {

  global CommonLib

  tk_messageBox -icon info -message {Creating Registration file...} -default ok

  if {[catch [list open [file join "$CommonLib" {Registration.tcl}] w] rfp]} {
    tk_dialog .error {Can't create Registration.tcl} \
	"Could not open [file join $CommonLib {Registration.tcl}]: $rfp"
    CleanupExit
  }

  global User Company Serial

  puts $rfp {#* Created by Home Librarian Register proc}
  puts $rfp {#* Do no Edit!}
  puts $rfp {#*}
  puts $rfp {}
  puts $rfp "global Registration"
  puts $rfp "set Registration(Name) \{$User\}"
  puts $rfp "set Registration(Organization) \{$Company\}"
  puts $rfp "set Registration(SN) \{$Serial\}"
  close $rfp
  tk_messageBox -default ok -icon info \
-message "[file join $CommonLib {Registration.tcl}] Created.\n\
If you have problems, you can send E-Mail to support@deepsoft.com, be sure to\n\
include the Serial Number ($Serial), and the platform ($SimpleOsVM-Tcl$tcl_version)\n\
in your E-Mail message."
}


MakeSh

if {[string length "$Serial"] > 0} {
  MakeReg
}


if {$SkipArchLib} {
  tk_messageBox -icon info \
	-message "Since there were no binary for $SimpleOsVM-Tcl$tcl_version, \n\
you will need to cd to $CommonSrc run configure, then make all, and make install\n\
before you can run the program." -default ok
}

if {![catch [list open [file join $CommonSrc {.archdir}] w] ofp]} {
  puts $ofp "$ArchLib"
  close $ofp
}


catch "file delete -force [file join $TempDir ALib]"
catch "file delete -force [file join $TempDir Lib]"
catch "file delete -force [file join $TempDir Doc]"
catch "file delete -force [file join $TempDir Src]"

tk_messageBox -icon info -message {Installation Complete!} -default ok

exit

