#!/usr/bin/env ruby
require 'amqpgen'

#
# Run a set of code generation templates.
#
if ARGV.size < 3
  puts <<EOS
Usage: #{ARGV[0]} OUTDIR  SPEC.xml [ ... ] TEMPLATE.rb [ ... ]
or:    #{ARGV[0]} OUTDIR  SPEC.xml [ ... ] all [ makefragment.mk ]

Parse all SPEC.xml files to create an AMQP model, run each TEMPLATE
putting the resulting files under OUTDIR. Prints a list of files
generated to standard output.

If OUTDIR is '-'  then just prints file list without generating files.
EOS
  exit 1
end

Outdir=ARGV[0]
Specs=ARGV.grep(/\.xml$/)
Amqp=AmqpRoot.new(*Specs)

# Run selected templates
if ARGV.any? { |arg| arg=="all" }
  templates=Dir["#{File.dirname __FILE__}/templates/*.rb"]
else
  templates=ARGV.grep(/\.rb$/)
end
templates.each { |t| load t }

def make_continue(lines) lines.join(" \\\n    "); end

# Generate makefile
makefile=ARGV.grep(/.mk$/)[0]
if makefile
  dir=Dir.getwd
  Dir.chdir File.dirname(__FILE__)
  generator_files=Dir["**/*.rb"] << File.basename(__FILE__)
  Dir.chdir dir
  rgen_generator=generator_files.map{ |f| "$(rgen_dir)/#{f}" }
  rgen_srcs=GenFiles.get.map{ |f| "#{Outdir}/#{f}" }

  File.open(makefile, 'w') { |out|
    out << <<EOS
# Generated makefile fragment.
# Including makefile defines $(rgen_dir) $(rgen_cmd) and $(specs).

rgen_generator=#{make_continue rgen_generator}

rgen_client_cpp=#{make_continue(rgen_srcs.grep(%r|/qpid/client/.+\.cpp$|))}

rgen_common_cpp=#{make_continue(rgen_srcs.grep(%r|qpid/framing/.+\.cpp$|))}

rgen_srcs=#{make_continue rgen_srcs}

# Header file install rules.
EOS
    ["framing", "client", "broker"].each { |ns|
      dir="qpid/#{ns}"
      dir_ = dir.tr("/", "_")
      regex=%r|#{dir}/.+\.h$|
      out << <<EOS
#{dir_}dir = $(includedir)/#{dir}
dist_#{dir_}_HEADERS = #{make_continue rgen_srcs.grep(regex)}

EOS
    }
    out << <<EOS
if GENERATE
$(rgen_srcs) $(srcdir)/#{File.basename makefile}: $(rgen_generator) $(specs)
	$(rgen_cmd)

# Empty rule in case a generator file is renamed/removed.
$(rgen_generator):
endif  
EOS
  }
end

