###############################################################################
#
# sourceList.eagle --
#
# Extensible Adaptable Generalized Logic Engine (Eagle)
# Public Source File Listing Tool
#
# Copyright (c) 2007-2012 by Joe Mistachkin.  All rights reserved.
#
# See the file "license.terms" for information on usage and redistribution of
# this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
# RCS: @(#) $Id: $
#
###############################################################################

package require Eagle

proc usage { error } {
  if {[string length $error] > 0} then {puts stdout $error}
  puts stdout "usage: [file tail [info nameofexecutable]]\
[file tail [info script]] <directory> <fileName>"
}

if {[llength $argv] == 2} then {
  #
  # NOTE: Get the directory where the source files reside.
  #
  set directory [lindex $argv 0]

  #
  # NOTE: Make sure the directory provided is not obviously invalid.
  #
  if {[string length $directory] > 0} then {
    #
    # NOTE: Get the file name that contains the list of excluded patterns.
    #
    set fileName [lindex $argv 1]

    #
    # NOTE: Make sure the file name provided is not obviously invalid.
    #
    if {[string length $fileName] > 0} then {
      #
      # NOTE: Read all the data out of the text file.
      #
      set data [readFile $fileName]

      #
      # NOTE: Normalize to Unix line-endings and [back]slash characters.
      #
      set data [string map [list \r\n \n \\ /] $data]; # Unix.

      #
      # NOTE: Split the file data into a list of lines.
      #
      set lines [split $data \n]

      #
      # NOTE: Get the complete list of candidate source files.
      #
      set sourceFileNames [findFilesRecursive [file join $directory *]]

      #
      # NOTE: We need the inverse lsearch procedure.
      #
      package require Eagle.Test

      #
      # NOTE: Check each candidate source file name against the list
      #       of excluded patterns.
      #
      foreach sourceFileName $sourceFileNames {
        #
        # NOTE: Make sure we are dealing with the canonical file name.
        #
        set sourceFileName [file normalize $sourceFileName]

        #
        # NOTE: Make sure the source file name does NOT match any of the
        #       exluced patterns.
        #
        if {[inverseLsearchGlob true $lines $sourceFileName] == -1} then {
          #
          # NOTE: Show the matched file name.
          #
          puts stdout $sourceFileName
        }
      }
    } else {
      usage "invalid file name"
    }
  } else {
    usage "invalid directory"
  }
} else {
  usage ""
}
