#!/usr/bin/env coffee
#
# Generates Web page (index.html), PDF (zombie.pdf) and Kindle Mobile
# (zombie.mobi).
#
# To use:
#
#   ./scripts/docs
#   open html/index.html
#   open html/zombie.pdf
#   open html/zombie.mobi
#
# You'll need wkhtmltopdf to generate the PDF:
#
#   brew install wkhtmltopdf
#
# And kindlegen available for download from Amazon.


{ execFile, exec }  = require("child_process")
File                = require("fs")
Path                = require("path")
render  = require("./markdown")


DOC_DIR   = Path.resolve("#{__dirname}/../doc/new")
HTML_DIR  = Path.resolve("#{__dirname}/../html")


# Always start with an empty html directory
prepareEmptyDirectory = (callback)->
  exec "rm -rf #{HTML_DIR}", ->
    exec "mkdir -p #{HTML_DIR}", (error)->
      callback(error)


# Generate the HTML file (Markdown, header IDs and layout) 
generateHTML = (callback)->
  console.log "Generating index.html ..."
  render "#{DOC_DIR}/README.md", "#{DOC_DIR}/layout.html", (error, html)->
    if error
      callback(error)
    else
      File.writeFile("#{HTML_DIR}/index.html", html, callback)


# Copy CSS, JS and images over
copyAssets = (callback)->
  exec "cp #{DOC_DIR}/*.{js,css} #{HTML_DIR}", callback


# Generate PDF file (requires HTML + assets)
generatePDF = (callback)->
  console.log "Generating zombie.pdf ..."

  pdfOptions = [
    "--disable-javascript",
    "--outline",
    "--print-media-type",
    "--title", "Zombie.js",
    "--allow", "images",
    "--footer-center", "Page [page]",
    "#{HTML_DIR}/index.html",
    "#{HTML_DIR}/zombie.pdf"
  ]
  execFile "wkhtmltopdf", pdfOptions, (error, stdout, stderr)->
    if error
      console.error("Note: if you haven't already, brew install wkhtmltopdf")
    callback(error)


# Generate Mobi file (requires HTML)
generateMobi = (callback)->
  console.log "Generating zombie.mobi ..."

  kindleOptions = [
    "-c2"
    "#{HTML_DIR}/index.html",
    "-o", "zombie.mobi"
  ]
  execFile "kindlegen", kindleOptions, (error, stdout, stderr)->
    console.log(stdout)
    callback()


# Asynchronously execute all functions from the first argument
executeFunctions = (fns, callback)->
  fn = fns[0]
  if fn
    fn (error)->
      if error
        callback(error)
      else
        executeFunctions(fns.slice(1), callback)
  else
    callback()


# These are the steps we execute in order
TASKS = [
  prepareEmptyDirectory
  copyAssets
  generateHTML
  generatePDF
  generateMobi
]

executeFunctions TASKS, (error)->
  if error
    console.error(error.stack)
    process.exit(1)
  else
    process.exit(0)
