MRuby::Gem::Specification.new('mruby-test-bench-fixture') do |spec|
  spec.authors = ["Nathan Ladd"]
  spec.homepage = "https://github.com/test-bench/test-bench-fixture"
  spec.licenses = ["MIT"]
  spec.summary = "Test object framework for Ruby and MRuby"

  spec.add_dependency 'mruby-class-ext'
  spec.add_dependency 'mruby-enum-ext'
  spec.add_dependency 'mruby-hash-ext'
  spec.add_dependency 'mruby-kernel-ext'
  spec.add_dependency 'mruby-metaprog'
  spec.add_dependency 'mruby-method'
  spec.add_dependency 'mruby-object-ext'
  spec.add_dependency 'mruby-numeric-ext'
  spec.add_dependency 'mruby-struct'
  spec.add_dependency 'mruby-toplevel-ext'

  spec.add_dependency 'mruby-logger'
  spec.add_dependency 'mruby-ostruct'
  spec.add_dependency 'mruby-stringio'
  spec.add_dependency 'mruby-tempfile'

  spec.add_dependency 'mruby-require', :github => 'test-bench/mruby-ruby-compat', :path => 'mrbgems/require'
  spec.add_dependency 'mruby-public-send', :github => 'test-bench/mruby-ruby-compat', :path => 'mrbgems/public-send'

  spec.mrblib_dir = 'lib'

  spec.test_rbfiles = []

  loader_files = ['lib/test_bench/fixture.rb']

  if ENV.fetch('MRUBY_COMPILE_CONTROLS', 'on') == 'on'
    loader_files << 'lib/test_bench/fixture/controls.rb'
  end

  loader_files.each do |loader_file|
    loader_file = File.join(__dir__, loader_file)

    require_statement_pattern = /^[[:blank:]]*require[[:blank:]]+['"](.*)['"]/

    File.read(loader_file).scan(require_statement_pattern) do |(feature)|
      file = File.join(__dir__, spec.mrblib_dir, feature)

      file << '.rb' unless file.end_with?('.rb')

      if File.exist?(file)
        spec.rbfiles << file
      end
    end

    spec.rbfiles << loader_file

    compiled_features_h = File.join(__dir__, 'src', 'compiled_features.h')

    File.open(compiled_features_h, 'w') do |compiled_features|
      compiled_features.puts <<~C99
      /* Generated by #{__FILE__} */

      #ifndef MRB_#{spec.funcname.upcase}_COMPILED_FEATURES_H
      #define MRB_#{spec.funcname.upcase}_COMPILED_FEATURES_H

      #include <mruby.h>

      static const char* const mrb_#{spec.funcname}_compiled_features[] = {
      C99

      lib_dir = Pathname.new(File.join(__dir__, spec.mrblib_dir))

      spec.rbfiles.each do |file|
        feature = Pathname.new(file).relative_path_from(lib_dir).sub_ext('')

        compiled_features.puts <<~C99
        \t"#{feature}",
        C99
      end

      compiled_features.puts <<~C99
      \tNULL
      };

      static mrb_int mrb_#{spec.funcname}_compiled_features_count = #{spec.rbfiles.length};

      #endif /* MRB_#{spec.funcname.upcase}_COMPILED_FEATURES_H */

      /* Generated by #{__FILE__} */
      C99
    end
  end
end
