# Make sure that archflags does not include ppc if we're # on Intel x86 processor on Mac, and that we use the proper arch if `uname`.chomp == “Darwin”

RUBY_PLATFORM =~ /darwin(\d+)/
darwin_version = $1.to_i

arch =
  if darwin_version >= 10
    'x86_64'
  else
    %x`uname -p`.chomp
  end

ENV["ARCHFLAGS"] = "-arch #{arch}"

end

require 'mkmf' require 'rbconfig'

# # A script to override some defaults in mkmf.rb for C++ code # compilation. # # If this looks like a big hack, that's because it is. #

def init_mkmf_rice(config = CONFIG)

# Set some defaults that we got from autoconf -- they're more likely
# to be correct than what Ruby was built with
$CXX = "@CXX@"
$LIBS = "@RUBY_LIBS@"
$LIBRUBYARG = "@RUBY_LIBRUBYARG@"
$LIBRUBYARG_STATIC = "@RUBY_LIBRUBYARG_STATIC@"
$RICE_CPPFLAGS = "@RICE_CPPFLAGS@"
$RICE_LDFLAGS = "@RICE_LDFLAGS@"
$RICE_PREFIX = File.join(File.dirname(File.expand_path(__FILE__)))

$RICE_USING_MINGW32 = @RICE_USING_MINGW32@

# We use this for the samples
$DEFLIBPATH.unshift(with_config('libpath')) if with_config('libpath')

lib_dirs = []

lib_dir = "#{$RICE_PREFIX}/lib"
lib64_dir = "#{$RICE_PREFIX}/lib64"

lib_dirs << "-L#{lib_dir}" if File.directory?(lib_dir)
lib_dirs << "-L#{lib64_dir}" if File.directory?(lib64_dir)

$CPPFLAGS << " #{$RICE_CPPFLAGS} -I#{$RICE_PREFIX}/include"
$LDFLAGS << " #{$RICE_LDFLAGS} #{lib_dirs.join(" ")} -lrice"

# Turn on debugging and verbose warnings by default on compilers that
# support it
$CXXFLAGS = ''
if $CXX == 'g++'
  $CXXFLAGS << ' -Wall -g'
end

# Fix-up the linker used for confidence tests
TRY_LINK.sub!(/^#{Regexp.quote("$(CC)")}/, $CXX)
TRY_LINK.sub!(/^#{config['CC']}/, $CXX)
TRY_LINK.sub!(/#{Regexp.quote("$(CFLAGS)")}/, "$(CXXFLAGS)")

# Set $LDSHARED_CXX to the linker to be used for C++ libraries (usually
# the C++ compiler itself)
case config['target_os']
when 'darwin'
  $LDSHARED_CXX = \
    replace_cc_with_cxx(config['LDSHARED']) + \
    ' -read_only_relocs suppress'
when 'mswin32'
  if $RICE_USING_MINGW32 then
    init_rice_mkmf_cross_compile_mingw2_for_vc6
  end
else
  $LDSHARED_CXX = \
    replace_cc_with_cxx(config['LDSHARED'])
end

end

def replace_cc_with_cxx(str)

return str.sub(
    /^(cc|\$\(CC\)|#{CONFIG['CC']})(?=\s)/,
    $CXX)

end

def init_rice_mkmf_cross_compile_mingw2_for_vc6

$LDSHARED_CXX = "#{$CXX} -shared -s"
$OBJEXT = 'o'
$DLDFLAGS.gsub!(/^-link.*\.pdb$/, '')

constants = {
  :TRY_LINK =>
    "#{$LDSHARED_CXX} -oconftest $(INCFLAGS) $(CPPFLAGS) " +      "$(CFLAGS) $(src) $(LIBPATH) $(LDFLAGS) $(ARCH_FLAG) " +      "$(LOCAL_LIBS) $(LIBS)",
  :LINK_SO =>
    "#{$LDSHARED_CXX} $(DLDFLAGS) $(LIBPATH) -o$@ " +      "$(OBJS) $(LOCAL_LIBS) $(LIBS)",
  :LIBARG =>
      '-l%s',
  :LIBPATHFLAG =>
      ' -L %s',
  :COMPILE_RULES =>
      %w[.%s.%s:],
  :RULE_SUBST =>
      '%s',
  :COMPILE_CXX =>
      '$(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) -c $<',
  :OUTFLAG =>
      '-o',
}

constants.each do |name, value|
  Object.instance_eval { remove_const name }
  Object.const_set(name, value)
end

end

class Object

alias_method :configuration_orig, :configuration
def configuration(srcdir)
  configuration = configuration_orig(srcdir)
  configuration.each do |config|
    # Make sure we link the extension using the C++ compiler
    config.gsub!(/^LDSHARED\s*=.*$/, "LDSHARED = #{$LDSHARED_CXX}")

    # Make sure set the C++ flags correctly
    config.gsub!(/^CXXFLAGS\s*=.*$/, "CXXFLAGS = $(CFLAGS) #{$CXXFLAGS}")
  end
  configuration << "\nCXX = #{$CXX}"
  return configuration
end

alias_method :link_command_orig, :link_command
def link_command(ldflags, opt='', libpath=$DEFLIBPATH|$LIBPATH)
  link_command = link_command_orig(ldflags, opt, libpath)
  return RbConfig::expand(
      link_command,
      'CXXFLAGS' => "#{$CXXFLAGS}")
end

alias_method :create_header_orig, :create_header
def create_header(header = 'extconf.hpp')
  create_header_orig(header)
end

alias_method :create_makefile_orig, :create_makefile
def create_makefile(target, srcprefix = nil)
  makefile_creator = RiceMakefileCreator.new
  makefile_creator.create_makefile(target, srcprefix)
end

end

class RiceMakefileCreator

def create_makefile(target, srcprefix)
  create_makefile_orig(target, srcprefix)
end

class MakefileWriter
  def self.new(file, mode)
    file = super(file, mode)
    if block_given? then
      begin
        yield file
      ensure
        file.close if not file.closed?
      end
    else
      return file
    end
  end

  def initialize(file, mode)
    @file = File.open(file, mode)
  end

  def print(*strings)
    strings.each do |string|
      # Make sure -lruby comes after -lrice (necessary on some
      # platforms)
      string = string.to_s.gsub(/^(LIBS\s*=\s*)(#{Regexp.quote($LIBRUBYARG)})\s+(.*)\s+(#{$LIBS})$/, '\1\3\2 \4')
      @file.print(string)
    end
  end

  def printf(format, *args)
    @file.printf(format, *args)
  end

  def puts(*strings)
    print(*strings.flatten.map { |s| "#{s}\n" })
  end

  def close
    @file.close
  end

  def closed?
    return @file.closed?
  end
end

def open(file, mode, &block)
  # Intercept makefile output using the MakefileWriter
  if file == 'Makefile' then
    return MakefileWriter.new(file, mode, &block)
  else
    return super(file, mode, &block)
  end
end

end

init_mkmf_rice