#!/usr/bin/ruby
require 'stringio'
require 'yaml'
require 'ostruct'

presentation = File.basename(File.dirname(File.expand_path(__FILE__)))
presentation = open("#{presentation}.txt") {|file| file.read}
$pages=presentation.split(/^#/)
$header=OpenStruct.new(YAML.load($pages.first))

xref=Hash.new {|hash, key| hash[key] = Array.new;}
$link = []
sect='title'
$pages.length.times do |page|
  next if page == 0
  $pages[page].gsub!(/\A([-\w]+):\s+/,'')
  sect = $1 if $1
  xref[sect] << page
  $link[page] = sect
  $link[page] += "-#{xref[sect].length}" if xref[sect].length > 1
end

require 'cgi'
require 'rubygems'
require 'redcloth'
def render(page, base, n)
  title, content = page.split(/\n/,2)
  puts '<!DOCTYPE html>'
  puts '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">'
  puts '  <head>'
  puts "    <meta charset='utf-8'/>"
  puts "    <title>#{title.strip} - #{$header.subtitle}</title>"
  $header.script.each do |script|
    puts "    <script src='#{script}'></script>"
  end
  $header.stylesheet.each do |stylesheet|
    puts "    <link rel='stylesheet' href='#{stylesheet}'/>"
  end

  puts "    <link rel='next' href='#{$link[n+1]}'/>" if n<$pages.length-1
  puts "    <link rel='prev' href='#{$link[n-1]}'/>" if n>1
  puts '  </head>'
  puts
  puts '  <body>'
  puts '    <header>'
  puts "      <h1><a href='#{$link[1]}'>#{$header.title}</a></h1>"
  puts "      <p>#{$header.date}</p>"
  puts '    </header>'
  puts
  puts '    <article>'
  puts '      <header>'
  puts "        <h3>#{title.strip}</h3>"
  puts '      </header>'
  puts
  content.gsub!(/^\{\{\{.*?\}\}\}\n/m) do |block|
    block.gsub!(' ', '&#160;')
    lines = block.split("\n")
    block.gsub!(/> (.*)/, '&gt; <b>\1</b>')
    "<fieldset>\n<legend>#{lines[0].gsub('{','').strip}</legend>\n" +
      "<p class='code'>#{lines[1..-2].join("<br/>\n")}</p>\n</fieldset>\n\n"
  end
  rc = RedCloth.new(content)
  rc.hard_breaks = false
  puts rc.to_html.gsub(/^/,'      ')
  puts '    </article>'
  puts
  puts '    <footer>'
  print $header.watermark.gsub(/^/,'      ')
  puts '    </footer>'
  puts '  </body>'
  puts
  puts '</html>'
rescue 
  puts $!
  puts '<pre>'
  puts $!.backtrace
  puts '</pre>'
end

if ENV['REQUEST_URI'] =~ /^(.*[?\/])(.*)/
  script = '' # $1
  ARGV.unshift $2
else
  script = ''
end

ARGV[0] = $link.index(ARGV[0]) || ARGV[0]
n=(ARGV.first.to_s.empty? ? 1 : ARGV[0].to_i)

if ENV['REQUEST_URI'] or n>0
  if n>0
    puts "Content-type: application/xhtml+xml\r\n\r" if ENV['QUERY_STRING']
    render $pages[n], script, n
  else
    puts "status: 404 Not Found\r\n\r\nNot Found"
  end
else
  if ARGV.include? 'clean'
    require 'fileutils'
    Dir.chdir 'static' do
      Dir['*'].each do |file|
        next if file.include? '.'
        next if File.directory? file
        next if $link.include? file
        next if $header.stylesheet.include? file
        next if $header.script.include? file
        FileUtils.rm file
      end
    end
  end

  $pages.length.times do |page|
    next if page == 0
    begin
      $stdout = StringIO.open('','w')
      render $pages[page], script, page
      dest = "static/#{$link[page]}"
      if $stdout.string != (open(dest) {|file| file.read} rescue '')
        open(dest,'w') {|file| file.write($stdout.string)}
      end
    ensure
      $stdout = STDOUT
    end
  end
end
