#!/usr/local/bin/ruby
=begin
 ******************************************************************************
 * Copyright 1990-2010 MBARI
 * MBARI Proprietary Information. All rights reserved.
 ******************************************************************************
 * Summary  : Ruby file compilation script
 * Filename : compile.rb
 * Author   : Virrey/Henthorn
 * Project  : Benthic Rover/SES
 * Version  : 2
 * Created  : June 2010
 * Modified : August 2010
 ******************************************************************************
=end

#####
# compile_dir
#
# Compile all the *.rb files in the current working directory
#
def compile_dir()

  ##
  # Get a list of the .rb files in the current directory
  #
  filelist = Dir.glob("*.rb")

  return 0 if (filelist.length == 0)  # No ruby files found

  ##
  # Iterate through the file list and send them to ruby compiler.
  # Keep a tally of how many failed compilation.
  #
  bad = 0
  puts("\n======== #{Dir.pwd} ========\n")

  filelist.each do |f|

    # Write the filename and some "."
    #
    n = STDOUT.write("#{f}")
    STDOUT.flush

    for i in 1..3
      STDOUT.write(".")
      STDOUT.flush
    end

    # Write the standard output of the compilation right-justified
    #
    pad = " " * (50-n)
    STDOUT.write(pad)
    r = system("ruby -c #{f}")

    # Flag any offending filenames and increment the bad file count
    #
    unless(r)
      flag = "^" * n
      STDOUT.write("#{flag}\n\n")
      STDOUT.flush
      bad += 1
    end
  end

  return bad
end

#########
# Script starts here
#

# Save the current directory so we can return
#
home = Dir.pwd

# Total number of bad files
#
total = 0

# No args - just compile the ruby files in the current directory
#
if (ARGV.length == 0)
  total = compile_dir()
else

  # Go to each directory and compile the ruby files.
  # Keep track of the total number of bad files.
  # 
  ARGV.each do |d|
    next unless(File.directory?(d))

    Dir.chdir(d)
    total += compile_dir()
    Dir.chdir(home)
  end
end

# Report the number of bad files, if any.
#
puts("\n\t>>> #{total} compilation failure <<<\n\n") if (total == 1)
puts("\n\t>>> #{total} compilation failures <<<\n\n") if (total > 1)
