#! /usr/local/bin/ruby

$".push 'mkmf.rb' #"

if ARGV[0] == 'static'
  $force_static = TRUE
  ARGV.shift
elsif ARGV[0] == 'install'
  $install = TRUE
  ARGV.shift
elsif ARGV[0] == 'clean'
  $clean = TRUE
  ARGV.shift
end

$extlist = []

$cache_mod = FALSE;
$lib_cache = {}
$func_cache = {}
$hdr_cache = {}

#$dllopt = '-MD'
$dllopt = ''

if File.exist?("config.cache") then
  f = open("config.cache", "r")
  while f.gets
    case $_
    when /^lib: ([\w_]+) (yes|no)/
      $lib_cache[$1] = $2
    when /^func: ([\w_]+) (yes|no)/
      $func_cache[$1] = $2
    when /^hdr: (.+) (yes|no)/
      $hdr_cache[$1] = $2
    end
  end
  f.close
end

def older(file1, file2)
  if !File.exist?(file1) then
    return TRUE
  end
  if !File.exist?(file2) then
    return FALSE
  end
  if File.mtime(file1) < File.mtime(file2)
    return TRUE
  end
  return FALSE
end

#LINK = "cl -o conftest.exe -I../.. -Zi -O -I. %s  conftest.c %s >  nul"
LINK = "cl -o conftest.exe -Zi -O  %s  conftest.c %s >  nul"
CPP = "cl -E  -I../.. -I../../missing -I../../win32 -I. -Zi -O %s conftest.c >  nul"

def try_link(libs)
  #print(format("try #{LINK}", $CFLAGS, $LDFLAGS, libs))
  #system(format(LINK, $CFLAGS, $LDFLAGS, libs))
  print(format("try #{LINK}\n", $CFLAGS, libs))
  system(format(LINK, $CFLAGS, libs))
end

def try_cpp
  system(format(CPP, $CFLAGS))
end

def have_library(lib, func)
  #print format("have_library(%s, %s)\n", lib, func)
  if $lib_cache[lib]
    if $lib_cache[lib] == "yes"
      if $libs#
	$libs = lib + ".lib " + $libs 
      else
	$libs = lib + ".lib "
      end
      return TRUE
    else
      return FALSE
    end
  end

  cfile = open("conftest.c", "w")
  cfile.printf "\
#include <windows.h>
#include <winsock.h>
int main() { return 0; }
int t() { %s(); return 0; }
", func
  cfile.close

  begin
    if $libs
      libs =  lib + ".lib " + $libs 
    else
      libs =  lib + ".lib"
    end
    #print "libs=#{libs}\n"
    unless try_link(libs)
      #print "fail : #{libs}\n"
      $lib_cache[lib] = 'no'
      $cache_mod = TRUE
      return FALSE
    end
  ensure
    system "rm -f conftest*"
  end

  $libs = libs
  $lib_cache[lib] = 'yes'
  $cache_mod = TRUE
  return TRUE
end

def have_func(func)
  if $func_cache[func]
    if $func_cache[func] == "yes"
      $defs.push(format("-DHAVE_%s", func.upcase))
      return TRUE
    else
      return FALSE
    end
  end

  cfile = open("conftest.c", "w")
  cfile.printf "\
#include <windows.h>
#include <winsock.h>
//char %s();
int main() { return 0; }
int t() { %s(); return 0; }
", func, func
  cfile.close

  libs = $libs
  libs = "" if libs == nil

  begin
    #print "libs=#{libs}\n"
    unless try_link(libs)
      $func_cache[func] = 'no'
      $cache_mod = TRUE
      return FALSE
    end
  ensure
    system "rm -f conftest*"
  end
  $defs.push(format("-DHAVE_%s", func.upcase))
  $func_cache[func] = 'yes'
  $cache_mod = TRUE
  return TRUE
end

def have_header(header)
  if $hdr_cache[header]
    if $hdr_cache[header] == "yes"
      header.tr!("a-z./\055", "A-Z___")
      $defs.push(format("-DHAVE_%s", header))
      return TRUE
    else
      return FALSE
    end
  end

  cfile = open("conftest.c", "w")
  cfile.printf "\
#include <%s>
", header
  cfile.close

  begin
    unless try_cpp
      $hdr_cache[header] = 'no'
      $cache_mod = TRUE
      return FALSE
    end
  ensure
    system "rm -f conftest*"
  end
  $hdr_cache[header] = 'yes'
  header.tr!("a-z./\055", "A-Z___")
  $defs.push(format("-DHAVE_%s", header))
  $cache_mod = TRUE
  return TRUE
end

def create_header()
  if $defs.length > 0
    hfile = open("extconf.h", "w")
    for line in $defs
      line =~ /^-D(.*)/
      hfile.printf "#define %s 1\n", $1
    end
    hfile.close
  end
end

def create_makefile(target)

  if $libs and "obj" == "obj"
    libs = $libs.split
    for lib in libs
      lib.sub!(/(.*)/, '"\1.lib"') if /.lib$/ !~ lib
    end
    $defs.push(format("-DEXTLIB='%s'", libs.join(",")))
  end
  $libs = "" unless $libs

  mfile = open("Makefile", "w")
  mfile.printf "\
SHELL = $(COMPSEC)

#### Start of system configuration section. ####

srcdir = .
VPATH = .

CC = cl

CFLAGS   = %s -I../.. -I../../missing -I../../win32 -I. -O -DNT %s #$CFLAGS %s

RUBYLIB  = ../../ruby.lib
DLDFLAGS =  /DLL
LDSHARED = 
", if $static then "" else "-fpic" end, $dllopt, $defs.join(" ")

  if $force_static
  print "static\n"
  else
  print "non static\n"
  end

  mfile.printf "\

libdir = /usr/local/lib/ruby/i386-mswin32


#### End of system configuration section. ####
"
  mfile.printf "LOCAL_LIBS = %s\n", $local_libs if $local_libs
  mfile.printf "LIBS = %s\n", $libs
  mfile.printf "OBJS = "
  if !$objs then
    $objs = Dir["*.c"]
    for f in $objs
      f.sub!(/\.c$/, ".obj")
    end
  end
  mfile.printf $objs.join(" ")
  mfile.printf "\n"

  dots = if "ginstall -c" =~ /^\// then "" else "../" end
  mfile.printf "\
TARGET = %s.%s

INSTALL = %sginstall -c

DEFFILE = %s.def

all:            $(TARGET)

clean:;         @rm -f *.obj *.lib *.exp vc*.pdb *.bak *.def
		@rm -f Makefile extconf.h conftest.*

realclean:      clean
", target,
    if $force_static then "lib" else "dll" end, dots, target

  if !$static
    mfile.printf "\

install:        $(libdir)/$(TARGET)

$(libdir)/$(TARGET): $(TARGET)
	@test -d $(libdir) || mkdir $(libdir)
	$(INSTALL) $(TARGET) $(libdir)/$(TARGET)
"
  else
    mfile.printf "\

install:;
"
  end

  if $force_static
    mfile.printf "\
$(TARGET): $(OBJS)
	lib /OUT:$(TARGET) $(OBJS)
"
  else
    mfile.printf "\
$(DEFFILE): 
	echo $(DEFFILE)

$(TARGET): $(OBJS)  $(DEFFILE)
	cl -DLL -o$(TARGET) $(OBJS) $(RUBYLIB) -link /DEF:$(DEFFILE)
"
  end

  if File.exist?("depend")
    dfile = open("depend", "r")
    mfile.printf "###\n"
    while line = dfile.gets()
      mfile.printf "%s", line
    end
    dfile.close
  end
  mfile.close
  if $static
    #printf format("push %s,%s\n", $static, target); ##debug print##
    $extlist.push [$static,target]
  end
end

#template of .def file.
def create_def(basename)
  defname = sprintf("%s.def", basename)
  f = open(defname, "w")
  f.printf "\
LIBRARY %s.dll
CODE LOADONCALL
DATA LOADONCALL
DESCRIPTION 'win32 %s.dll'
EXPORTS

	Init_%s
", basename, basename, basename
  f.close

end

def extmake(target)
  if $force_static or $static_ext[target]
    $static = target
  else
    $static = FALSE
  end

  return if $nodynamic and not $static

  $local_libs = nil
  $libs = nil
  $objs = nil
  $CFLAGS = nil
  $LDFLAGS = nil

  begin
    Dir.chdir target
    if $static_ext.size > 0 ||
      !File.exist?("./Makefile") ||
      older("./Makefile", "../Setup") ||
      older("./Makefile", "../extmk.rb") ||
      older("./Makefile", "./extconf.rb")
    then
      $defs = []
      if File.exist?("extconf.rb")
	load "extconf.rb"
      else
	create_makefile(target);
      end
    end

    if !File.exist?("#{target}.def")
        create_def(target)
    end

    if File.exist?("./Makefile")
      if $install
	system "nmake install"
	if File.directory? "./lib"
	  for i in Dir["./lib/*.rb"]
	    system "ginstall -c #{i} /usr/local/lib/ruby/i386-mswin32"
	  end
	end
      elsif $clean
	system "nmake clean"
      else
	#print "!!!make!!!\n"
	system "nmake all"
      end
    end
    if $static
      $extlibs = " "
      $extlibs += " " + $LDFLAGS if $LDFLAGS
      $extlibs += " " + $local_libs if $local_libs
      $extlibs += " " + $libs if $libs
    end
  ensure
    Dir.chdir ".."
  end
end

# get static-link modules
$static_ext = {}
if File.file? "./Setup"
  f = open("./Setup") 
  while f.gets()
    $_.chop!
    sub!(/#.*$/, '')
    next if /^\s*$/
    #print $_, "\n"

    if /^option +nodynamic/
      $nodynamic = TRUE
      next
    end
    $static_ext[$_.split[0]] = TRUE
  end
  f.close
end

for d in Dir["*"]
  File.directory?(d) || next
  File.file?(d + "/MANIFEST") || next
  
  d = $1 if d =~ /\/([\/]*)$/
  if $install
    print "installing ", d, "\n"
  elsif $clean
    print "cleaning ", d, "\n"
  else
    print "compiling ", d, "\n"
  end
  extmake(d)
end

if $cache_mod
  f = open("config.cache", "w")
  for k,v in $lib_cache
    f.printf "lib: %s %s\n", k, v
  end
  for k,v in $func_cache
    f.printf "func: %s %s\n", k, v
  end
  for k,v in $hdr_cache
    f.printf "hdr: %s %s\n", k, v
  end
  f.close
end

exit if $install or $clean
$extinit = " " unless $extinit
$extobjs = ""
if $extlist.size > 0
  for s,t in $extlist
  #for s,t in $static_ext
    #f = format("%s/%s.obj", s, t)
    #f = format("%s/%s.obj", s, s)
    l = format("%s/%s.lib", s, s)    
    if File.exist?(l)
      $extinit += format("\
\tInit_%s();\n\
\trb_provide(\"%s.o\");\n\
", s, s)
      $extobjs += "ext/"
      #$extobjs += f  # *.obj
      $extobjs += l   # *.lib
      $extobjs += " "
    else
      FALSE
    end
  end

  if older("extinit.c", "Setup")
    f = open("extinit.c", "w")
    f.printf "void Init_ext() {\n"
    f.printf $extinit
    f.printf "}\n"
    f.close
  end
  if older("extinit.obj", "extinit.c")
    cmd = "cl -Zi -O -I. -c extinit.c"
    print cmd, "\n"
    system cmd or exit 1
  end

  Dir.chdir ".."

  if older("ruby.exe", "ext/Setup") or older("ruby.exe", "miniruby.exe")
    `rm -f ruby.exe`
  end

  $extobjs = "ext/extinit.obj " + $extobjs
  #$extlibs = ""
  #print "EXTLIBS=#{$extlibs}\n"
  $extlibs.gsub!("-L/usr/local/lib", "") if $extlibs
  $extlibs.gsub!(" +", " ") if $extlibs
  #print "EXTLIBS=#{$extlibs}\n"

  system format('nmake ruby.exe EXTOBJS="%s" EXTLIBS="%s"', $extobjs, $extlibs)
else
  Dir.chdir ".."
  if older("ruby.exe", "miniruby.exe")
    `rm -f ruby.exe`
    `cp miniruby.exe ruby.exe`
  end
end
#Local variables:
# mode: ruby
#end:
