#! /usr/bin/env tclsh

# clean up the inotify issue.  We have two possible cases:
# 1. This arch has a binary for inotify or
# 2. it does not.
#
# This bit of code trims the packages directory to correctly represent
# Which inotify (if any) is to be used on this (the running) platform
#
# First figure out where the code is...

proc clean-file {f} {
  set out {}
  if [file exists $f] {
    if { [catch { file readlink $f} out1]  == 0 } {
      set f [file join [file dirname $out] $out1]
    }
    set out [file normalize $f]
  }
  return $out
}

set me [clean-file $::argv0]
lappend possible [file dirname $me]
if { [catch {info script} out] == 0 } {
  set out [clean-file $out]
  if { [catch {file dirname $out} it] == 0} {

    set tail [file tail $out]
    #      puts "start with [info script]"
    set it [file normalize $it]
    #      puts "found $it"
    lappend possible $it 
  }
}
lappend possible [pwd]
puts "looking in $possible"
set success 0
foreach testfile $possible  {
  #    puts "testing $testfile"
  if { [file exists $testfile/$tail]  == 1 } {
    set HomeDir "$testfile/packages"
    if {[file exists $HomeDir]} {
      set success 1
      break
    }
  }
}
if {$HomeDir != [file dirname $me]} {
  puts "Really bad news here.  The found dir ($HomeDir)
is not where I am running from([file dirname $me]).
I am NOT going there."
  exit 1
}

if {!$success} {
  puts "Could not find the required filerunner directory."
  puts "Looked in these locations: $possible"
  puts "Try cd-ing to the filerunner directory and running."
  puts "Done here."
  exit 1
}
puts "found $HomeDir & I am $me"
exit
if {$::tcl_platform(os) != "Linux"} {
  # In this case the whole of the inotify thing should just be 
  # removed...
  file delete -force $HomeDir/inotify
} else {
  set type $::tcl_platform(machine)
  if {$type in [glob -nocomplain \
		    -path $CODE/packages/inotify/ -type d -tails "*"]} {
    cd $HomeDir/packages/inotify/$type
    # we have the required code... move it and delete the rest
    foreach file [glob -nocomplain  "*"] {
      file copy $file $HomeDir/packages/inotify/$file
    }
    foreach dir [glob -nocomplain -type d \
		     -path $HomeDir/packages/inotify/ "*"] {
      file delete -force $dir
    }
    set type 1
  } else {
    # No binary for this arch, delete the whole thing
    # Do NOT use force here as we may have already done our
    # thing so the dir will not be empty.  Not using force keep it around.
    file delete $HomeDir/packages/inotify
  }
}
# Self distruct
file delete -force $me
exit 0
