#! /usr/bin/env tclsh
# -*- tcl -*-
# <20180121.1759.38>
# This file uses the version of inotify found in the same dir as run from
# to build a version of inotify for the current arch.

# We assume all the tools needed are present on the system, well we do,
# but the build code in the package will check all that out...
#

# first find a temp directory...
foreach ex {TMP TMPDIR} {
  if {[info exists env($ex)]} {
    lappend tmplist $env($ex)
  }
}
lappend tmplist "/tmp" "/temp"

set tmpdir {}

foreach tmpdir $tmplist {
  set tmpdir [file normalize $tmpdir]
  if {[file isdirectory $tmpdir] } {break}
}

if {$tmpdir == {}} {
  echo "Could not find a tmp dir in enviroment. Looked for:\
       \nTMP and TMPDIR\
       \nPlease fix this..."
  exit 1
}

# Make sure we have a location to put the result
set ok 0
set pos {~/.config/.fr ~/.fr}
foreach dir $pos {
  set dir [file norm $dir]
  if {[file isdir $dir]} {
    incr ok
    break
  }
}
if {$ok == 0} {
  puts "Could not find 'filerunners' config directory. It should be one of: \
        \n$pos"
  puts "It would appear that you have not run 'filerunner' yet."
  exit 0
}

set here [pwd]

set arch [file normalize [lindex [lsort [glob ./tcl-inotify-*]] end]]

cd $tmpdir
file delete -force inotify-work
file mkdir inotify-work
cd inotify-work

catch {exec  tar xfBp $arch} out

if {$out != {}} {
  # something went wrong...
  puts "$out"
  puts "That looks wrong.  Giving up..."
  exit 1
}

set wd [glob type d *]

if {[llength $wd] != 1} {
  puts "Expected one directory but found $wd"
  exit 1
}

cd $wd

set r [catch {exec ./configure} out]

# we expect r == 1 here as there is output which should be in 'out'
# spit out what configure had to say. 
 
puts "$out"

# To check if things seemed to go ok check for existance of:
# config.status
# Makefile
# pkgIndex.tcl
# config.log

# finely if config.log has the line "configure: exit 0"
#
foreach fl {config.status Makefile pkgIndex.tcl config.log} {
  if {![file exists $fl]} {
    lappend er $fl
  }
}
if {[info exists er]} {
  puts "\n\nLooks like something went wrong. Expected to find but did not,
       these file(s): $er"
  puts "Better look into this..."
  exit 1
}
catch {exec grep "configure: exit 0" config.log} out

if {$out != "configure: exit 0"} {
  puts "Expected to find 'configure: exit 0' in config.log but did not.
        message was $out"
  puts "Better look into this..."
  exit 1
}
catch {exec make} out

puts $out

# if this results in a .so file, we are done with the build...

set so [glob -nocomplain *.so]

if {[llength $so] != 1 } {
  puts "\n\nMake appears to have failed"  
  puts "Better look into this..."
  exit 1
}

file copy -force $so  pkgIndex.tcl [file normalize $dir]

puts "Sucess $so created and moved to [file normalize $dir]"

