#! /usr/bin/env tclsh
# -*- tcl -*- 
# run this with pwd in ./<something>
# i.e. it should be one dir lower that the things being indexed

# This script builds the config scripts (by calling buildConfig.tcl)
# putting them in the package area for "unix" and "mswindows"
# It then indexes the main (i.e. up one level) including frlib.

# Separate indexes are then made for package dirs unix, vfs and mswindows
    
# first do the config files
#

set pakPre "../packages"
puts "[pwd]"
foreach {platform flags} {unix ::MSW=0 mswindows ::MSW=1} {
  puts "building $platform config files"
  # If this is run on MSW, the tclsh will help keep things straight.
  # Another way is to pre load argc and source buildConfig.tcl...
  set out [exec tclsh ./buildConfig.tcl $flags out=$pakPre/$platform/config ]
  puts "$out"
}
puts "Done with config files"
set pat [concat [glob -tails -path ../ *.tcl] \
	     [glob -nocomplain -tails -path ../ frlib/*.tcl]]
lappend pat fr
#foreach file $pat {
 # if { $file != $main } {
 #   lappend dothis [file tail $file]
 # }
#}
puts "$argv"
set here [pwd]
set dothis [lsort $pat]
# puts "writing buildlist.tcl"
puts [open buildlist.txt w] "[join $dothis \n]"
eval "auto_mkindex .. $dothis"
if {$argv == {}} {
  puts "Make tclIndex for [file tail [file norm ..]] & [file tail [file norm ../frlib]]"
} else {
  puts "Make tclIndex for $here with $dothis"
}
cd $here
# And the package indexes...
foreach dr {unix mswindows} {
  set dir $pakPre/$dr
  puts "Make Package Index: [pwd] $dir"
  pkg_mkIndex $dir
}

# Here we take care of our platform packages
foreach dr {mswindows unix} {
  # Not sure if this is worth it or not...
  # The intent is to NOT put package files in the tclIndex
  # We build a comma seperated list of files to include
  set dir $pakPre/$dr
  set sors [glob -dir $dir -tail *.tcl]
  set package [read [open $dir/pkgIndex.tcl r]]
  set incl {}
  foreach sor $sors {
    # crude but it works..
    if {"$sor]]" ni $package} {
      lappend incl $sor
    }
  }
  set pat "\{[join $incl ","]\}"
  if {$argv == {}} {
    puts "Make tclIndex for $dir $pat"
  } else {
    puts "Make tclIndex $dir $pat"
  }
  auto_mkindex $dir $pat
}
auto_mkindex $here $here/*.tcl $here/../frlib/*.tcl
# Now remake all the package index files that are auto gened.
#
#
# puts "$here [pwd]"
puts ""
set argv [list $pakPre BackUps~]
source updatePkgIndexs.tcl

# and for our final act, lets make sure the permissions are right
# (if we are not on windows) for all the executables in the current dir

if {$::tcl_platform(platform) != "windows"} {
  foreach file [glob *] {
    if {[file exec $file]} {continue}
    set first [read [set fid [open $file r]] 5]
    close $fid
    #puts "file $file => $first"
    if {[string range $first 0 1] == "#!" } {
      # puts "doit"
      catch {exec chmod -c "0775" $file} ops
      puts "$ops"
    }
  }
}
