#!/usr/local/bin/tclsh
# -*- tcl -*-
#		Pool @mFullVersion@, as of @mDate@
#
# @comment generate package index out of given tclIndex and package name
#
# CVS: $Id: gen_pkg,v 1.3 1998/06/01 19:55:05 aku Exp $

if {[llength $argv] < 3} {
    puts stderr "Usage: $argv0 <pkgname> <pkgversion> <indexfile>"
    exit -1
}

set pkg_name [lindex $argv 0]
set pkg_vers [lindex $argv 1]
set index    [lindex $argv 2]

# disable autoloader, clear registry
unset auto_path

# 'unset auto_index' seems to be impossible, but this works
foreach e [array names auto_index] {
    unset auto_index($e)
}

# read index file, this populates the registry -> 'auto_index'
set dir @dir@
source $index

# determine the files used and map from files to procedures:

foreach p [array names auto_index] {
    #        [lindex $auto_index($p) 0] == "source"
    set file [lindex $auto_index($p) 1]

    # strip "$dir/" (which was transformed to "@dir@/" during 'source')
    regsub -- {^@dir@/} $file {} file

    lappend files($file) $p
}


set f [array names files]
if {[llength $f] == 0} {
    puts stdout "Index empty, no package possible"
    exit 0
}

set   pkg_index [file join [file dirname $index] pkgIndex.tcl]
set   pkg       [open $pkg_index w]
puts $pkg "# Tcl package index file, version 1.0"
puts $pkg "# This file is generated by the \"gen_pkg\" command"
puts $pkg "# and sourced either when an application starts up or"
puts $pkg "# by a \"package unknown\" script.  It invokes the"
puts $pkg "# \"package ifneeded\" command to set up package-related"
puts $pkg "# information so that packages will be loaded automatically"
puts $pkg "# in response to \"package require\" commands.  When this"
puts $pkg "# script is sourced, the variable \$dir must contain the"
puts $pkg "# full path name of this file's directory."
puts $pkg ""
puts $pkg "package ifneeded $pkg_name $pkg_vers \[list tclPkgSetup \$dir $pkg_name $pkg_vers \{"

foreach f [lsort $f] {
    puts stdout "$f [llength $files($f)]"
    puts -nonewline $pkg "\t\{$f source \{"

    set procs ""

    foreach p [lsort $files($f)] {
	append procs "$p "
    }

    puts -nonewline $pkg [string trimright $procs]

    puts $pkg "\}\}"
}

puts  $pkg "\}\]"
close $pkg
