#!/usr/bin/ruby
# coding: utf-8

require 'nokogiri'

LogLevel=1
raise ArgumentError, 'Language and source/destination files not specified' if ARGV.size != 3
lang = ARGV[0]
srcfile = ARGV[1]
dstfile = ARGV[2]

f=File.open(srcfile)
xml = Nokogiri::XML(f)

def log(level,what)
  indicators = %w(! • # -)
  if level >= LogLevel
    print indicators[level]
  else
    print "\n%s %s\n" % ['*' * (level+1), what]
  end
end

log 0, 'Including the Spanish version introduction'
if intro = File.open('extra/es/intro_es.xml', 'r').read rescue nil
  xml.search('preface').last.after( intro )
else
  log 0, ' -!- Introduction text not found or empty'
end

log 0, 'replace images with translated versions'
xml.search('imagedata').each do |img|
  # Included images are in the 'Pictures' directory. Translated images
  # are in Pictures/[langcode]/. Only translated images need to be
  # included.
  orig_img = img.attributes['fileref'].text
  trans_img = orig_img.gsub(/Pictures/, "Pictures/#{lang}")
  next if orig_img == trans_img

  if File.exists?(trans_img)
    log 1, 'Replaced %s by %s' % [orig_img, trans_img]
    img.set_attribute('fileref', trans_img)
  end
end

log 0, 'Final editorial requests: Attributions on top, as in other chapters, also for prefaces'
xml.search('preface').each do |pref|
  title = pref.search('title').first
  attrib = pref.search('blockquote').last
  attrib_text =  attrib.inner_text.gsub(/\s+/,' ')

  # Some formatting issues we need to modify
  attrib_text.gsub!(/Paul y Sarah/, 'Paul <?latex \textup{>y<?latex } > Sarah')
  attrib_text.gsub!(/Merkley (CEO.*)/, 'Merkley <citetitle>\1</citetitle>')
  attrib_text.gsub!(/Wolf (Ins.*)/, 'Wolf <citetitle>\1</citetitle>')

  attrib.remove
  title.after('<blockquote><attribution>%s</attribution></blockquote>' % attrib_text)
  log 1, 'Moved: %s' % attrib_text
end

log 0, 'Replace legal info by the information assembled by our publisher'
if legal = File.open('extra/es/legal_info.xml', 'r').read rescue nil
  xml.search('colophon').first.inner_html = legal
end

log 0, 'Add a colophon at the end'
# Doing this the dirty, non-DocBooky way: I'm adding a large <?latex
# ... ?> section to the last appendix. This should probably go in the
# <colophon> section, but it's already used.
#
# A cleaner way would be to replace the <xsl:param
# name="latex.enddocument"> section in pdf_es.xsl — But it gets
# trickier :-Þ
if colophon = File.open('extra/es/colophon.tex', 'r').read rescue nil
  xml.search('appendix').last.search('para').last.after('<?latex %s ?>' % colophon)
end


log 0, 'Writing processed file'
# Unable to figure out API way to replace DOCTYPE
data = xml.to_xml()
File.open(dstfile, 'w') {|f| f.write(data)}
