###############################################################################
#
# license_tag.tcl --
#
# Extensible Adaptable Generalized Logic Engine (Eagle)
# License Tag 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: $
#
###############################################################################

set path [file normalize [file dirname [info script]]]
set lib_path [file join $path .. .. lib]

lappend auto_path $lib_path
package require Eagle.Library 1.0
namespace import -force ::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>"

  #
  # NOTE: Indicate to the caller, if any, that we have failed.
  #
  exit 1
}

if {$argc == 1} then {
  set dir [lindex $argv 0]

  if {[file isdirectory $dir]} then {
    set license_tag [readFile [file join $path template license_tag.txt]]

    foreach file [findFilesRecursive [file join $dir *.cs]] {
      if {![string match -nocase *commercial* $file] && \
          ![string match -nocase *proprietary* $file] && \
          ![string match -nocase *generated* $file]} then {
        set data [readFile $file]

        if {[string first {See the file "license.terms"} $data] == -1} then {
          set new_file [file tail $file]
          set tag [subst $license_tag]
          set data [appendArgs $tag $data]

          if {![file writable $file]} then {
            file attributes $file -readonly 0
          }

          writeFile $file $data
        }
      }
    }
  } else {
    usage [appendArgs "argument \"" $dir "\" is not a directory."]
  }
} else {
  usage ""
}
