#!/usr/bin/ruby -w

require 'asciidoctor'
require 'erb'
require 'pathname'
#require 'fileutils'

generate_all = (ARGV.length == 1 and ARGV[0] == '-a')
if generate_all
  puts "Generating all pages!"
end

# Read the page template
template_file = 'template.html'
template = File.read(template_file)
@erb = ERB.new(template)
@erb.filename = template_file

new_pages = []
mod_pages = []

def make_page(infile, outfile)
  # note: safe mode 1 allows include[] macros but paths must be within parent dir
  doc = Asciidoctor.load_file infile, header_footer: false, safe: 1

  # Set vars used in template - note that the "_" prefix prevents an
  # 'assigned but unused variable' warning in Ruby.
  _title     = doc.attributes['title'] || "Untitled Page"
  _subtitle  = doc.attributes['subtitle'] || ""
  _created   = doc.attributes['created'] || ""
  _updated   = doc.attributes['updated'] || ""
  _updated_reason   = doc.attributes['updated_reason'] || ""
  _tags      = doc.attributes['tags'] || ""
  _draft     = doc.attributes['draft'] || ""
  _body      = doc.convert
  _generated = Time.now
  _copyright_year = Time.now.strftime("%Y")
  _pkgblog   = false
  _cards     = false

  # see if it's a pkgblog path - super dumb/easy way :-)
  if infile.to_s =~ /pkgblog/
    _pkgblog = true
  end

  # see if it's a cards/ path - super dumb/easy way :-)
  if infile.to_s =~ /cards/
    _cards = true
  end


  File.open(outfile, 'w') do |f|
    f.puts @erb.result(binding)
  end
end

Pathname.glob("src/**/*.adoc").each do |infile|
  needs_update = false

  # Wow, replacing ".adoc" not with ".html", but with NOTHING!
  outfile = infile.sub_ext('')

  #puts "input: #{infile} (#{infile.mtime})"

  if not outfile.exist?
    needs_update = true
    new_pages << outfile
  else
    if (outfile.mtime < infile.mtime) or generate_all
      needs_update = true
      mod_pages << outfile
    end
  end

  if needs_update
    make_page infile, outfile
  end
end

puts "NEW: #{new_pages.join(' ')}"
puts "MOD: #{mod_pages.join(' ')}"
