require "bundler"
Bundler.setup(:default)

require "rake/clean"
require "rscons"

NAME = "jes"
GTEST_VERSION = "1.7.0"

base_env = Rscons::Environment.new do |env|
  env.build_root = "build"
  env["CCFLAGS"] += ["-Wall", "-O2"]
  env["CFLAGS"] << "-std=gnu99"
  env["CXXFLAGS"] << "-std=gnu++11"
  if RUBY_PLATFORM =~ /cygwin/
    env["CC"] = "i686-pc-mingw32-gcc"
    env["CXX"] = "i686-pc-mingw32-g++"
    env["LDFLAGS"] += ["-static-libgcc", "-static-libstdc++"]
    ruby_location = ENV["RUBY_PATH"] || "/cygdrive/c/Ruby193"
    sdl2_location = ENV["SDL2_PATH"] || "/cygdrive/c/apps/SDL2"
    freetype_location = ENV["FREETYPE_PATH"] || "/cygdrive/c/apps/freetype"
    env.parse_flags!(<<-EOF)
      -I#{ruby_location}/include/ruby-1.9.1/i386-mingw32
      -I#{ruby_location}/include/ruby-1.9.1
      -L#{ruby_location}/lib
      -Wl,--enable-auto-image-base,--enable-auto-import
      -lmsvcrt-ruby191 -lshell32 -lws2_32 -limagehlp -lshlwapi

      -I#{freetype_location}/include/freetype2
      -L#{freetype_location}/lib -lfreetype

      -I#{sdl2_location}/include -Dmain=SDL_main
      -L#{sdl2_location}/i686-w64-mingw32/lib -lmingw32 -lSDL2main -lSDL2 -mwindows
    EOF
  else
    env.parse_flags!("!pkg-config --cflags --libs ruby-1.9")
    env.parse_flags!("!freetype-config --cflags --libs")
    env.parse_flags!("!sdl2-config --cflags --libs")
  end
  if RUBY_PLATFORM =~ /mingw|cygwin/
    env["LIBS"] += ["opengl32"]
  else
    env["LIBS"] += ["GL"]
  end
end

task :default do
  base_env.clone(clone: :all) do |env|
    env.Program("bin/jes", Dir["src/**/*.{cc,c}"])
  end
end

task :test do
  base_env.clone(clone: :all) do |env|
    env.build_root = "build/test"
    env["CPPPATH"] << "src"
    env["CPPPATH"] << "gtest-#{GTEST_VERSION}/include"
    env["CPPPATH"] << "gtest-#{GTEST_VERSION}"
    sources = Dir["gtest-#{GTEST_VERSION}/src/gtest-all.cc",
                  "gtest-#{GTEST_VERSION}/src/gtest_main.cc",
                  "src/**/*.{cc,c}",
                  "test/src/**/*.cc"] - ["src/main.cc"]
    if RUBY_PLATFORM =~ /linux/
      env["LIBS"] << "pthread"
    end
    env.Program("build/tests", sources)
  end
  system("./build/tests")
end

task :all => :default

task :clean do
  Rscons.clean
end
