#---
# Author::  Ian Yang
# Created:: <2010-06-10 18:20:38>
#+++
#
# Generate keys

# search Keys:: to find all keys
require 'rubygems'
require 'rake'
require 'fileutils'
require 'date'

source = File.dirname(File.dirname(File.expand_path(__FILE__)))

driver_source = File.join(source, "core", "common")
process_source = File.join(source, "process")
merchant_score_source = File.join(source, "core", "mining-manager", "merchant-score-manager")

keys_inl = File.join(driver_source, "Keys.inl")
keys_cpp = File.join(driver_source, "Keys.cpp")

files = FileList.new
[driver_source, process_source, merchant_score_source].each do |dir|
  ["h", "cpp", "inl"].each do |ext|
    files.include File.join(dir, "**", "*.#{ext}")
  end
end

keys_hash = {}

files.each do |f|
  File.open(f) do |out|
    fname = f.sub(%r{^.*[/\\\|]sf1r-engine[/\\\|]source[/\\\|]}, "")
    out.each_with_index do |l, i|
      l.scan(/Keys\s*::\s*([_a-zA-Z]+)/) do |match|
        unless match[0] =~ /^BOOST_PP/
          keys_hash[match[0]] ||= []
          keys_hash[match[0]] << "#{fname}:#{i + 1}"
        end
      end
    end
  end
end

File.open(keys_inl, "w") do |out|
  out.write <<HEADER
/**
 * @file sf1r/driver/Keys.inl
 * @date Created <#{DateTime.now.strftime "%Y-%m-%d %H:%M:%S"}>
 *
 * This file is generated by generators/driver_keys.rb by collecting keys
 * from source code. Do not edit this file directly.
 */

#define SF1_DRIVER_KEYS \\
HEADER

  keys = keys_hash.keys.sort
  last = keys.pop
  keys.each do |key|
    out.write "(#{key})\\\n"
  end
  out.write "(#{last})\n"

  out.write "\n\n/* LOCATIONS\n"
  
  # location info
  keys << last
  keys.each do |key|
    out.write "\n#{key}\n"
    keys_hash[key].each do |location|
      out.write "  #{location}\n"
    end
  end

  out.write "\n*/\n"
end

# recompile cpp
FileUtils.touch keys_cpp
