#!/usr/bin/luajit

-- luacheck: ignore loadstring
local loadstring = loadstring or load

local basename = arg[1]
local path = arg[1] .. "/app/" .. arg[1]

local tocfile = io.open(arg[2], "r")
if not tocfile then
   return false
end
local doc = tocfile:read("*a")
tocfile:close()

local toc = assert(loadstring(doc))()

local yaml = require("yaml")
local meta = yaml.loadpath(arg[3])

local share = "https://yayinlar.viachristus.com/"

local infofile = io.open(arg[4], "w")
if not infofile then
   return false
end

local infow = function (str, endpar)
   str = str or ""
   endpar = endpar and "\n" or ""
   infofile:write(str .. "\n" .. endpar)
end

infow("TITLE:")
infow(meta.title, true)

infow("SUBTITLE:")
infow(meta.subtitle, true)

if meta.creator then
   for _, v in ipairs(meta.creator) do
      if v.role == "author" then
         meta.author = v.text
      end
   end
end

infow("AUTHOR:")
infow(meta.author, true)

infow("ABSTRACT:")
infow(meta.abstract, true)

infow("SINGLE PDF:")
infow(share .. path .. "-uygulama.pdf", true)

infow("MEDIA:")
infow(share .. path .. "-square-poster.jpg", true)
infow(share .. path .. "-wide-poster.jpg", true)
infow(share .. path .. "-banner-poster.jpg", true)

local labels = {}
local breaks = {}

if #toc > 0 then
   -- Label the first chunk before we skip to the content
   labels[1] = toc[1].label[1]

   -- Drop the first TOC entry, the top of the file will be 1
   table.remove(toc, 1)

   local lastpage = 1
   breaks = { 1 }

   -- Get a table of major (more that 2 pages apart) TOC entries
   -- TODO: should this be ipairs()?
   for _, tocentry in pairs(toc) do
      if tocentry.level <= 2 then
         local pageno = tonumber(tocentry.pageno)
         if pageno > lastpage + 2 then
            table.insert(breaks, pageno)
            labels[#breaks] = tocentry.label[1]
            lastpage = pageno
         else
            labels[#breaks] = tostring(labels[#breaks]) .. ", " .. tostring(tocentry.label[1])
         end
      end
   end

   -- Convert the table to page rages suitable for pdftk
   for i, v in pairs(breaks) do
      if i ~= 1 then
         breaks[i - 1] = breaks[i - 1] .. "-" .. v - 1
      end
   end
   breaks[#breaks] = breaks[#breaks] .. "-end"
end

-- Output a list suitable for shell script parsing
for i, v in pairs(breaks) do
   local n = string.format("%03d", i - 1)
   local out = basename .. "-uygulama-" .. n .. ".pdf"
   local out2 = path .. "-uygulama-" .. n .. ".pdf"

   -- Fieds expected by makefile to pass to pdftk
   print(v, out)

   -- Human readable info for copy/paste to the church app
   infow("CHUNK " .. i - 1 .. ":")
   infow(labels[i])
   infow(share .. out2, true)
end

infofile:close()
