#
# <20200301.1519.42>
#
# There are two 'which' commands. Both have to do with MSW's WSL environment.
#
# With out WSL, they return the same thing as auto_execok.
# With WSL, if 'auto_execok' failes they search on the other side of the house
# for something to execute. Thus there is a version for MSW and one for linux.

# This is the side for MSW
package require fileutil

namespace eval which {}

# We set up a PATH here by looking at the WSL files.
# If /mnt/ is empty, the distro is not active, skip it.
# Path is set up by calls to pathmunge in /etc/profile (/usr/sbin /usr/local/sbin)
# and added to in the user .bashrc

proc which {name} {
  if {[set tmp [auto_execok $name]] != {}} {return $tmp}

  # we now go through the env(PATH) and return the first one we find that is
  # executable. For scripts, we try to find the executable that goes with it.
  # This may fail as some scripts start with /bin/sh or /bin/bash and then
  # go else where.

  foreach path [split $env(PATH) :\;] {
    if {![file exist $path/$name]} {continue}

    # Well the name matches...
    lassign {} exp
    set ans [::fileutil::fileType $path/$name]
    if {[set ex [string match "* executable *" $ans]]} {break}
    if {![string match "* script *"    $ans]} {continue}
    # This is a bit more complicated...
    #
    set dat [read [set pid [open $path/$name r]] 2000]
    set dat [split $dat \n]
    set line [string trim [lindex $dat 0]]
    set exprog [string range $line [string last " " $line]+1 end]
    set prog [file tail $exprog]
    if {$prog in {sh bash}} {
      # This could be a dodge to 'exec' another script handler
      foreach line $dat {
	set line [string trim $line]
	if {[string length $line] == 0 ||\
		[string index $line 0] == "#"} {continue}
	if {![string match "exec *" $line]} {break}
	# We found an exec, pull out the target...
	set trimln [string trim [string range [string first " " $line] end]]
	set prog [string range $trimln 0 [string first " " $trimln]-1]
      }
      
    }
    # We have a program name, lets requre to get its full path
    set exp [which $prog]
    # if we can not find something to run the script, try the next path
    if {$exp == {}} {continue}
    break
  }
  # The music stopped, lets see what we have
  if {!$ex} {return {}}
  if {$exp != {}} {
    return [list $exp $path/$name]
  }
  return [list $path/$name]
}
