
# self configure the package file
# 'package provide <xx> <ver> must be in the first 4000 chars.
# ver should be m.m1.m2.... (as many as desired)
# At this time we can handle multiple packages, however, each
# package must be only one file (at this time).

namespace eval packs {
  proc genpacks {dir} {
    set oldPwd [pwd]
    cd $dir
    set verNow "0.0.0.0"
    foreach file [glob *.tcl] {
      if {$file == "pkgIndex.tcl"} {continue}
      set data [read [set pid [open $file r]] 4000]
      close $pid
      foreach line [split $data \n] {
	set line [string trim $line]
	if {[catch {lassign $line pak pro name ver}] != 0} {continue}
	
	if {$pak == "package" &&\
		$pro == "provide"} {
	  if {![info exists packs($name)]} {
	    set packs($name) "0.0.0"
	  }
	  
	  if {[package vcompare $ver $packs($name)] == 1} {
	    set packs($name) $ver
	    set packs($name,file) $file
	    break
	  }
	}
      }
    }
    cd $oldPwd
    # This open will likely fail in installed systems as they are usually
    # in a protected part of the file system
    if {[catch {open $dir/packages w} fid]} {
      set fid 0
    } else {
      puts $fid "# This file for debug only. It shows what package statement were\
      \n# by the pkgIndex.tcl in this dir.\n"
    }
    foreach pak [array names packs -regexp {^[^,]+$}] {
      package ifneeded $pak $packs($pak)\
	  [list source [file join $dir $packs($pak,file)]]
      if {$fid != 0} {
	puts $fid "package ifneeded $pak $packs($pak) \
      	[list source [file join $dir $packs($pak,file)]]"
      }
    }
    array unset packs
    catch {close $fid}
  }
}
::packs::genpacks $dir
