# Ruby Treasures 0.3
# Copyright (C) 2002 Paul Brannan <paul@atdesk.com>
# 
# You may distribute this software under the same terms as Ruby (see the file
# COPYING that was distributed with this library).
# 
# Ruby Treasures 0.2
# Copyright (C) 2002 Paul Brannan <paul@atdesk.com>
# 
# You may distribute this software under the same terms as Ruby (see the file
# COPYING that was distributed with this library).
# 
# Run this Ruby script to prepare the RubyTreasures distribution for
# publication.

require 'find'
require 'ftools'

system("ruby extconf.rb --norecurse")
system("make docs")
puts "Removing Makefile"
File.rm_f('Makefile')

license = IO.readlines('LICENSE')

ruby_license_comment = license.map { |i| i.sub(/^/, '# ') }
c_license_comment = ["/*\n"] + license.map { |i| i.sub(/^/, ' * ') } + [" */\n"]

def rm_rf(dir)
  Dir.foreach(dir) do |f|
    if not f =~ /\.?\.$/ then
      filename = File.join(dir, f)
      if File.directory?(filename) then
        rm_rf(filename)
      else
        puts "Removing file #{filename}"
        File.rm_f(filename)
      end
    end
  end
  puts "Removing directory #{dir}"
  Dir.rmdir(dir)
end

Find.find('.') do |file|
  if File.directory?(file) then
    case file
      when /\/CVS$/
        # Remove CVS directories
        rm_rf(file)
      else
        # Remove empty directories
        entries = Dir.entries(file)
        entries.delete('.')
        entries.delete('..')
        entries.delete('CVS')
        if entries.length == 0 then
          rm_rf(file)
        end
    end
  else
    case file
      when /\.rb$/
        # Add LICENSE to ruby sources
        puts "Adding license to #{file}"
        lines = ruby_license_comment + IO.readlines(file)
        File.open(file, 'w') do |out|
          lines.each do |line|
            out.puts line
          end
        end
      when /\.c$/
        # Add LICENSE to C sources
        puts "Adding license to #{file}"
        lines = c_license_comment + IO.readlines(file)
        File.open(file, 'w') do |out|
          lines.each do |line|
            out.puts line
          end
        end
      when /~$/
        # Remove temporary files
        puts "Removing file #{file}"
        File.rm_f(file)
    end
  end
end
