#!/usr/bin/ruby
# -*- encoding: utf-8 -*-
require 'erb'

contentsdir = 'contents.d/'
tmpdir = 'tmp/'

class Layout
  require './bin/render_rss.rb'
  include RenderRss
  extend ERB::DefMethod
  tmpldir = 'template/'
  def_erb_method('layout', File.join(tmpldir, 'layout.html.erb'))
  def_erb_method('layout_top', File.join(tmpldir, 'layout-top.html.erb'))
  def_erb_method('layout_pkginfo', File.join(tmpldir, 'layout-pkginfo.html.erb'))
  def_erb_method('layout_members', File.join(tmpldir, 'layout-members.html.erb'))
  def_erb_method('layout_goods', File.join(tmpldir, 'layout-goods.html.erb'))
end

Dir::glob(File.join(contentsdir, "*.html")) do |filename|

  template = ERB.new(IO.read(filename),nil,'<>')
  filebasename = File.basename(filename)
  newfile = open(File.join(tmpdir, filebasename), "w")

  header_title_base = 'Vine Linux'
  
  layout = Layout.new
  
  case filebasename
  when /index.html/
    layout_type = "layout_top"
  when /projectvine.html/
    layout_type = "layout_members"
  when /package-info.html/
    layout_type = "layout_pkginfo"
  when /goods.html/
    layout_type = "layout_goods"
  else
    layout_type = "layout"
  end
  
  title=File.read(filename).lines.grep(/h1 class=\"title/).first
  if title
    $header_title = header_title_base+' - '+title.gsub(/.*>(.*)<.*/,"\\1").chomp
  else
    $header_title = header_title_base
  end

  newfile.puts layout.send(layout_type) { template.result }
  newfile.close

end
