set executable [info script]
if {$executable == ""} {
    set executable [info nameof]
}

set package [lindex [split [file tail [file dirname $executable]] " "] 0]

cd InstallationCode

# source a platform specific file if it exists.
if {[file exists $tcl_platform(platform)_script.tcl]} {
    source $tcl_platform(platform)_script.tcl
}

switch -- $tcl_platform(platform) {
    "macintosh" {
	if {[llength [set compressed [glob -nocomplain *.{hqx,bin,sit}]]]} {
	    error "Please decompress these files in the InstallationCode\
	      folder, and then run again: $compressed"
	}
    }
    "windows" {
    }
    "unix" {
    }
}

set base [file dirname $tcl_library]

# FIRST: Copy all shared libraries
foreach dll [glob -nocomplain *[info sharedlibextension]] {
    catch {file delete [file join $base $dll]}
    file copy $dll [file join $base $dll]
}

proc recursively_copy {{to ""}} {
    global base
    # this '*/' pattern works on MacOS as well as Windows
    foreach dir [glob -nocomplain */] {
    	catch {file mkdir [file join $base $to $dir]}
    	cd $dir
    	foreach f [glob -nocomplain *] {
	    if {[file isfile $f]} {
        	catch {file delete [file join $base $to $dir $f]}
		file copy $f [file join $base $to $dir $f]
	    } 
	}
        recursively_copy [file join $to $dir]
        cd ..
    }
}

# SECOND: Copy all directories of Tcl code
recursively_copy 

# THIRD: Add to the pkgIndex file

if {[file exists pkgIndex.tcl]} {
    set fin [open pkgIndex.tcl r]
    set index [read $fin]
    close $fin

    if {[file exists [file join $base pkgIndex.tcl]]} {
        set fin [open [file join $base pkgIndex.tcl] r]
        set oldindex [read $fin]
        close $fin
    } else {
	set oldindex ""
    }
    if {[regexp "# START: $package installation" $oldindex]} {
	regsub "# START: $package installation.*# END: $package installation\[\r\n\]" $oldindex "" oldindex
    }
    set fout [open [file join $base pkgIndex.tcl] w]
    puts -nonewline $fout $oldindex
    puts $fout "# START: $package installation"
    puts $fout $index
    puts $fout "# END: $package installation"
    close $fout
}

cd ..
if {[file exists Readme]} {
    set fin [open Readme r]
    set contents [read $fin]
    close $fin

    text .t -yscrollcommand ".s set"
    .t insert end $contents
    scrollbar .s -command ".t yview"
    grid .t .s -sticky news
    grid rowconfigure .t 0 -weight 1
    grid columnconfigure .t 0 -weight 1
}

frame .b
grid .b
button .b.exit -text "Installation successful.  Click to Exit" -command exit

if {[file exists Tests]} {
    button .b.tests -text "Run tests" -command "cd Tests ; console show ; auto_reset ; source all"
    grid .b.exit .b.tests
} else {
    grid .b.exit
}
console show
