#!/usr/bin/env ruby

if ARGV.first == "--help" or ARGV.size == 0
  puts <<-EOF
usage: formatter.rb SOURCE_FILE

Creates ebooks in various formats and if there is a pdf with same name in
same folder, it creates a booklet ready for duplex printing (long-edge).

Source file has to be supported by libreoffice. Requires libreoffice (soffice),
pdfjam (pdfbook), and calibre (ebook-convert)
Copyright 2014 Robert Riemann - licensed under GPL v2 or higher.
  EOF
  exit
end

source = File.expand_path ARGV.first
abort("ERROR: File #{source} doesn't exist.") unless File.exists? source

basename = File.basename source, '.*'

puts "source #{source}"

# prepare for input filter of ebook-convert
%x[soffice --headless --convert-to docx #{source}]

docxfile = basename + '.docx'

# convert to ebook
%x[ebook-convert #{docxfile} #{basename}.mobi] # kindle old
%x[ebook-convert #{docxfile} #{basename}.azw3] # kindle new
%x[ebook-convert #{docxfile} #{basename}.epub] # default, legacy

# is there a pdf ?
pdffile = "#{File.dirname(source)}/#{basename}.pdf"
puts "pdf #{pdffile}"
if File.exists? pdffile
  %x[pdfbook --booklet false --signature '32' --suffix 'booklet' #{pdffile}]
end