#!/usr/bin/ruby

#    Copyright 2018 Couchbase, Inc.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

require 'json'

paths = Dir[File.join(__dir__, 'queries', '*.json')].sort
File.open(File.join(__dir__, 'queries.h'), 'w+') do |out|
  out.puts("// This file was generated by queries.rb")
  out.puts("typedef struct fts_query_str { const char *comment; size_t query_len; const char *query; } fts_query_str;")
  out.puts("size_t num_queries = #{paths.size};")
  out.puts("fts_query_str queries[#{paths.size + 1}] = {")
  paths.each do |path|
    lines = File.readlines(path)
    comment = lines[1].gsub(%r{^//\s*}, '').strip
    query = lines.reject { |line| line.start_with?('//') }.join
    query_str = JSON.generate(JSON.parse(query))
    out.puts("{#{comment.inspect},\n #{query_str.size},\n #{query_str.inspect}},\n\n")
  end
  out.puts("{NULL, 0, NULL}};")
end
