#!/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 analytics_query_str { const char *comment; size_t query_len; const char *query; } analytics_query_str;")
  out.puts("size_t num_queries = #{paths.size};")
  out.puts("analytics_query_str queries[#{paths.size + 1}] = {")
  paths.each do |path|
    lines = File.readlines(path)
    lines.delete_at(0)
    comment, query = lines.partition { |line| line.start_with?('//') }
    comment_str = comment.map { |line| line.sub(%r(^//\s*), '').strip }.join(' ')
    query_str = JSON.generate(JSON.parse(query.join.strip))
    out.puts("{#{comment_str.inspect},\n #{query_str.size},\n #{query_str.inspect}},\n\n")
  end
  out.puts("{NULL, 0, NULL}};")
end
