#! /usr/bin/env tclsh

# <20220417.1118.23>

# This script builds a tcl script to tell the wrap version of filerunner
# about the included packages.  The un-wrapped version does not need this,
# but the lack of glob to find files in the wrapped filerunner, requires
# this.
# 
# The file this builds is intended to be sourced, so make every thing global.
#
# Input should be the file name of the file containing the list of files to
# be wrapped.  We assume that that name also supplies the directory where
# we will put the resulting script and also the directory where the packages
# are to be found.
#
# A second parameter will be used as the root directory. This is defaulted to
# "$::glob(lib_fr)"
#
# And the third parameter is where to put the result. Default is  

#
proc echo {mess} {
  if {$::v} {
    puts "$mess"
  }
}
set v 0

set rootSupplied 0
set root [lindex $argv 1]
if {$root == {}} {
  set root "\$::glob(lib_fr)"
} else {
  set rootSupplied 1
  if {[file exists $root]} {
    set root [file norm $root]
  }
}
set file [lindex $argv 0]
if {![file exists $file]} {
  puts "Could not find file $file.  Out of here!"
  exit 1
}

set ffile [file norm [file join [pwd] $file]]
set dir [file dirname $ffile]
set diro [file dirname $dir]
if {$rootSupplied} {
  set diro $root
}

echo "full file name: $ffile \nDirname $dir \nResult to $diro"

set fid [open $ffile r]
set fido [open $diro/packageLinks.tcl w]

puts $fido "# This file is automaticly generated by the 'wrap' process.\
           \n# The actual generating file is 'makepackagelinks.tcl'.\
           \n# It is only used by the wrapped filerunner to over come\
           \n# the 'glob' short comming of the wrap code.\
           \n\n# It is intended that this file will be sourced by filerunner\
           \n# after it has found its library.\
           \n\n"

foreach line [split [read $fid] \n] {
  echo "Checking $line"
  if {[file tail $line] == "pkgIndex.tcl"} {
    set pkgDir [file dir $line]
    echo "Found $line"
    if {![string match *twapi/pkgIndex.tcl $line]} {
      puts $fido \
	  "lappend ::auto_path  $root/$pkgDir"
    }
  }
}
close $fido
close $fid
exit 0
