#
# The Make tool routes to extension Makefile(s).
# At this point it's designed to support extconf.rb design.
#
# TODO: Perhaps make a true compiler class in the future.
# TODO: win32 cross-compile.

module Reap

  class Manager

    def extensions
      @extensions ||= metadata.extensions || 'ext/**/extconf.rb'
    end

    # Return list of extconf.rb scripts.

    def extension_scripts
      [extensions].flatten.collect do |ext|
        Dir.glob(ext)
      end.flatten
    end

    # Return list of directory locations of extconf.rb scripts.

    def extension_directories
      glob(extension_scripts).map do |ext|
        File.dirname(ext)
      end
    end

    # Check to see if this project has extensions that need to be compiled.

    def compiles?
      !extension_directories.empty?
    end

    # Compile extensions.

    def make
      make_extconf
      make_target
    end

    # Compile static.

    def make_static
      make_extconf
      make_target 'static'
    end

    # Remove enouhg compile products for a clean compile.

    def make_clean
      make_target 'clean'
    end

    # Remove all compile products.

    def make_distclean
      make_target 'distclean'
    end

    # TODO: Clobber should get rid of Makefiles too.

    #alias_method :clobber_make, :make_distclean

    # Create Makefile(s).

    def make_extconf
      extensions.each do |file|
        directory = File.dirname(file)
        next if File.exist?(File.join(directory, 'Makefile'))
        cd(directory) do
          sh "ruby #{File.basename(file)}"
        end
      end  
    end

    private

    def make_target(target='')
      extension_directories.each do |directory|
        cd(directory) do
          sh "make #{target}"
        end
      end  
    end


    # Eric Hodel said NOT to copy the compiled libs.
    #
    #task :copy_files do
    #  cp "ext/**/*.#{dlext}", "lib/**/#{arch}/"
    #end
    #
    #def dlext
    #  Config::CONFIG['DLEXT']
    #end
    #
    #def arch
    #  Config::CONFIG['arch']
    #end

    # Cross-compile for Windows. (TODO)

    #def make_mingw
    #  abort "NOT YET IMPLEMENTED"
    #end

  end

end