begin
  require 'rake/gempackagetask'
rescue LoadError
end
require 'rake/clean'

require 'rbconfig'
include Config

ON_WINDOWS        = RUBY_PLATFORM =~ /mswin32/i 
PKG_NAME          = 'json'
PKG_VERSION       = File.read('VERSION').chomp
PKG_FILES         = FileList["**/*"].exclude(/CVS|pkg|coverage|Makefile/).exclude(/\.(so|bundle|o|#{CONFIG['DLEXT']})$/)
EXT_ROOT_DIR      = 'ext/json/ext'
EXT_PARSER_DIR    = "#{EXT_ROOT_DIR}/parser"
EXT_PARSER_DL     = "#{EXT_ROOT_DIR}/parser.#{CONFIG['DLEXT']}"
EXT_PARSER_SRC    = "#{EXT_PARSER_DIR}/parser.c"
PKG_FILES << EXT_PARSER_SRC
EXT_GENERATOR_DIR = "#{EXT_ROOT_DIR}/generator"
EXT_GENERATOR_DL  = "#{EXT_ROOT_DIR}/generator.#{CONFIG['DLEXT']}"
EXT_GENERATOR_SRC = "#{EXT_GENERATOR_DIR}/generator.c"
RAGEL_CODEGEN     = %w[rlcodegen rlgen-cd].find { |c| system(c, '-v') }
RAGEL_DOTGEN      = %w[rlgen-dot rlgen-cd].find { |c| system(c, '-v') }
RAGEL_PATH        = "#{EXT_PARSER_DIR}/parser.rl"
CLEAN.include 'doc', 'coverage', FileList['diagrams/*.*'],
  FileList["ext/**/*.{so,bundle,#{CONFIG['DLEXT']},o,obj,pdb,lib,manifest,exp,def}"],
  FileList["ext/**/Makefile"]


desc "Installing library (pure)"
task :install_pure => :version do
  ruby 'install.rb'
end

task :install_ext_really do
  sitearchdir = CONFIG["sitearchdir"]
  cd 'ext' do
    for file in Dir["json/ext/*.#{CONFIG['DLEXT']}"]
      d = File.join(sitearchdir, file)
      mkdir_p File.dirname(d)
      install(file, d)
    end
  end
end

desc "Installing library (extension)"
task :install_ext => [ :compile, :install_pure, :install_ext_really ]

task :install => :install_ext

desc "Compiling extension"
task :compile => [ EXT_PARSER_DL, EXT_GENERATOR_DL ]

file EXT_PARSER_DL => EXT_PARSER_SRC do
  cd EXT_PARSER_DIR do
    ruby 'extconf.rb'
    if ON_WINDOWS
      sh 'nmake'
      sh "mt -manifest parser.#{CONFIG['DLEXT']}.manifest -outputresource:parser.#{CONFIG['DLEXT']};2"
    else
      sh 'make'
    end
  end
  cp "#{EXT_PARSER_DIR}/parser.#{CONFIG['DLEXT']}", EXT_ROOT_DIR
end

file EXT_GENERATOR_DL => EXT_GENERATOR_SRC do
  cd EXT_GENERATOR_DIR do
    ruby 'extconf.rb'
    if ON_WINDOWS
      sh 'nmake'
      sh "mt -manifest generator.#{CONFIG['DLEXT']}.manifest -outputresource:generator.#{CONFIG['DLEXT']};2"
    else
      sh 'make'
    end
  end
  cp "#{EXT_GENERATOR_DIR}/generator.#{CONFIG['DLEXT']}", EXT_ROOT_DIR
end

desc "Generate parser with ragel"
task :ragel => EXT_PARSER_SRC

task :ragel_clean do
  rm_rf EXT_PARSER_SRC
end

file EXT_PARSER_SRC => RAGEL_PATH do
  cd EXT_PARSER_DIR do
    sh "ragel -x parser.rl | #{RAGEL_CODEGEN} -G2"
  end
end

desc "Generate diagrams of ragel parser (ps)"
task :ragel_dot_ps do
  root = 'diagrams'
  specs = []
  File.new(RAGEL_PATH).grep(/^\s*machine\s*(\S+);\s*$/) { specs << $1 }
  for s in specs 
    sh "ragel -x #{RAGEL_PATH} -S#{s} | #{RAGEL_DOTGEN} -p|dot -Tps -o#{root}/#{s}.ps"
  end
end

desc "Generate diagrams of ragel parser (png)"
task :ragel_dot_png do
  root = 'diagrams'
  specs = []
  File.new(RAGEL_PATH).grep(/^\s*machine\s*(\S+);\s*$/) { specs << $1 }
  for s in specs 
    sh "ragel -x #{RAGEL_PATH} -S#{s} | #{RAGEL_DOTGEN} -p|dot -Tpng -o#{root}/#{s}.png"
  end
end

desc "Generate diagrams of ragel parser"
task :ragel_dot => [ :ragel_dot_png, :ragel_dot_ps ]

desc "Testing library (pure ruby)"
task :test_pure => :clean do
  ruby '-v -I lib tests/runner.rb'
end

desc "Testing library (extension)"
task :test_ext => :compile do
  ruby '-v -I ext:lib tests/runner.rb'
end

desc "Benchmarking parser (pure)"
task :benchmark_parser_pure do
  ruby '-I lib benchmarks/benchmark_parser.rb pure'
end

desc "Benchmarking generator (pure)"
task :benchmark_generator_pure do
  ruby '-I lib benchmarks/benchmark_generator.rb pure'
  ruby 'benchmarks/benchmark_rails.rb'
end

desc "Benchmarking library (pure)"
task :benchmark_pure => [ :benchmark_parser_pure, :benchmark_generator_pure ]

desc "Benchmarking parser (extension)"
task :benchmark_parser_ext => :compile do
  ruby '-I ext:lib benchmarks/benchmark_parser.rb ext'
end

desc "Benchmarking generator (extension)"
task :benchmark_generator_ext => :compile do
  ruby '-I ext:lib benchmarks/benchmark_generator.rb ext'
  ruby 'benchmarks/benchmark_rails.rb'
end

desc "Benchmarking library (extension)"
task :benchmark_ext => [ :benchmark_parser_ext, :benchmark_generator_ext ]

task :benchmark do
  puts "Benchmarking extension variant"
  Rake::Task[:benchmark_ext].invoke
  puts "Benchmarking pure variant"
  Rake::Task[:benchmark_pure].invoke
end

desc "Testing library with coverage" # XXX broken
task :coverage do
  system 'RUBYOPT="" rcov -x tests -Ilib tests/runner.rb'
end

desc "Create RDOC documentation"
task :doc => [ :version, EXT_PARSER_SRC ] do
  sh "rdoc -m JSON -S -o doc lib/json.rb #{FileList['lib/json/**/*.rb']} #{EXT_PARSER_SRC} #{EXT_GENERATOR_SRC}"
end

if defined? Gem
  spec_pure = Gem::Specification.new do |s|
    s.name = 'json_pure'
    s.version = PKG_VERSION
    s.summary = "A JSON implementation in Ruby"
    s.description = ""

    s.files = PKG_FILES

    s.require_path = 'lib'

    s.bindir = "bin"
    s.executables = ["edit_json.rb"]
    s.default_executable = "edit_json.rb"

    s.has_rdoc = true
    s.rdoc_options <<
      '--title' <<  'JSON -- A JSON implemention' <<
      '--main' << 'JSON' << '--line-numbers'
    s.test_files << 'tests/runner.rb'

    s.author = "Florian Frank"
    s.email = "flori@ping.de"
    s.homepage = "http://json.rubyforge.org"
    s.rubyforge_project = "json"
  end

  Rake::GemPackageTask.new(spec_pure) do |pkg|
      pkg.need_tar = true
      pkg.package_files += PKG_FILES
  end

  spec_ext = Gem::Specification.new do |s|
    s.name = 'json'
    s.version = PKG_VERSION
    s.summary = "A JSON implementation as a Ruby extension"
    s.description = ""

    s.files = PKG_FILES

    s.extensions <<
      "#{EXT_PARSER_DIR}/extconf.rb" <<
      "#{EXT_GENERATOR_DIR}/extconf.rb"

    s.require_path = EXT_ROOT_DIR
    s.require_paths << 'ext'
    s.require_paths << 'lib'

    s.bindir = "bin"
    s.executables = ["edit_json.rb"]
    s.default_executable = "edit_json.rb"

    s.has_rdoc = true
    s.rdoc_options <<
      '--title' <<  'JSON -- A JSON implemention' <<
      '--main' << 'JSON' << '--line-numbers'
    s.test_files << 'tests/runner.rb'

    s.author = "Florian Frank"
    s.email = "flori@ping.de"
    s.homepage = "http://json.rubyforge.org"
    s.rubyforge_project = "json"
  end

  Rake::GemPackageTask.new(spec_ext) do |pkg|
    pkg.need_tar = true
    pkg.package_files += PKG_FILES
  end

  task :package_win => :compile do
    mkdir_p 'pkg'
    spec_win_ext = Gem::Specification.new do |s|
      s.name = 'json'
      s.platform = Gem::Platform::WIN32
      s.version = PKG_VERSION
      s.summary = "A JSON implementation as a Ruby extension"
      s.description = ""

      s.files = PKG_FILES.to_a <<
        "#{EXT_ROOT_DIR}/parser.#{CONFIG['DLEXT']}" <<
        "#{EXT_ROOT_DIR}/generator.#{CONFIG['DLEXT']}"

      s.require_path = EXT_ROOT_DIR
      s.require_paths << 'ext'
      s.require_paths << 'lib'

      s.bindir = "bin"
      s.executables = ["edit_json.rb", "prettify_json.rb"]
      s.default_executable = "edit_json.rb"

      s.has_rdoc = true
      s.rdoc_options <<
        '--title' <<  'JSON -- A JSON implemention' <<
        '--main' << 'JSON' << '--line-numbers'
      s.test_files << 'tests/runner.rb'

      s.author = "Florian Frank"
      s.email = "flori@ping.de"
      s.homepage = "http://json.rubyforge.org"
      s.rubyforge_project = "json"
    end

    gem_file = "json-#{spec_win_ext.version}-#{spec_win_ext.platform}.gem"
    Gem::Builder.new(spec_win_ext).build
    mv gem_file, 'pkg'
  end
end

task :mrproper => [ :ragel_clean, :clean ] do
  for dir in [ EXT_PARSER_DIR, EXT_GENERATOR_DIR ]
    cd(dir) {  rm_f 'Makefile' }
  end
end

desc m = "Writing version information for #{PKG_VERSION}"
task :version do
  puts m
  File.open(File.join('lib', 'json', 'version.rb'), 'w') do |v|
    v.puts <<EOT
module JSON
  # JSON version
  VERSION         = '#{PKG_VERSION}'
  VERSION_ARRAY   = VERSION.split(/\\./).map { |x| x.to_i } # :nodoc:
  VERSION_MAJOR   = VERSION_ARRAY[0] # :nodoc:
  VERSION_MINOR   = VERSION_ARRAY[1] # :nodoc:
  VERSION_BUILD   = VERSION_ARRAY[2] # :nodoc:
  VARIANT_BINARY  = #{!!ON_WINDOWS}
end
EOT
  end
end

if ON_WINDOWS
  task :release => [ :version, :clean, :package_win ]
else
  task :release => [ :version, :mrproper, :package ]
end

task :default => [ :version, :compile ]
