#!/usr/bin/env texlua

-- Build script for "StrukTeX" files

-- Identify the bundle and module: the module may be empty in the case where
-- there is no subdivision
bundle = ""
module = "struktex"

-- Location of main directory: use Unix-style path separators
-- Should match that defined by the bundle.
maindir = "."

-- the files to be installed
installfiles = {"*.sty"}

-- the files which should not be installed
excludefiles = {"*/TODO.md"}

-- these files are to copy for unpackaging
sourcefiles = {"*.dtx", "*.ins", "build.lua", "build-config.lua"}

-- these files are part of the documentation
docfiles = {"struktex.drv", "struktex.sty"}

-- these files get tags
tagfiles = {"*.sty"}

-- this file must be TeXed to unpack all
unpackfiles = {"struktex.dtx"}
-- unpackopts = "-interaction=batchmode"

-- create a TDS-suited .zip-file
packtdszip = true

-- Files to copy to unpacking when typesetting
typesetsourcefiles = {"struktex.sty"}

-- Files needed to support typesetting when "sandboxed"?
typesetsuppfiles = {"tex-bib.bib"}

-- only using the following engines for testing the code
checkengines    = checkengines or {"latex", "pdftex"}

-- install also documentation (doesn't work, because
-- there are no *.pdf-files in the unpacked directory
installfiles     = installfiles or {"*.pdf", "*.sty"}

-- Load the common build code
dofile(maindir .. "/build-config.lua")

-- specific settings for the StrukTeX development repo, used by l3build script

function prepare_contents(file)
  -- can't be set locally, so: set it back later on!
  typesetopts = "--output-format=dvi"
  tex(file)

  -- create .pdf-file from .dvi-source
  name = stripext(file)
  dvitopdf(name, typesetdir, typesetexe, true)
  run(typesetdir, "pdfcrop " .. name .. pdfext)
  ren(typesetdir, name .. "-crop" .. pdfext, name .. pdfext)
end

function print_log(log_message)
  print(log_message)
  return 0
end

function typeset(file)
  local name = jobname(file)

  typesetopts = "--output-format=pdf"
  local errorlevel = tex(file, typesetdir)

  print("\ntypeset.errorlevel:", errorlevel, "\n")

  if errorlevel == 0 then
    -- Return a non-zero errorlevel if anything goes wrong
    print("prepare additional information")
    errorlevel = (
      print_log("file: " .. file .. ", name: " .. name) +
        print_log("going to bibtex with >" ..  name .. "<") +
        bibtex(name, typesetdir) +
        print_log("\nbibtex done\n") +
        tex(file, typesetdir) +
        print_log("going to makeindex with", name) +
        makeindex(name, typesetdir, ".idx", ".ind", ".ilg", "gind.ist") +
        makeindex(name, typesetdir, ".glo", ".gls", ".glg", "gglo.ist") +
        print_log("\nmakeindex done\n") +
        tex(file, typesetdir)
                 )
    print_log("\ntypesetting done\n")
    ren(typesetdir, "struktex.pdf", "struktex." .. targetlanguage .. ".pdf")
    print_log("\nrenaming to struktex." .. targetlanguage .. ".pdf done\n")
  end

  return errorlevel
end

function setversion_update_line(line, date, release)
  local function get_date_release()
    -- get version information from git
    local f = io.popen("git describe", "r")
    local release = {}
    for entry in f:lines() do
      release[#release + 1] = entry
    end
    return os.date("%Y/%m/%d", os.time()), release[1]:sub(2, -1)
  end

  date, release = get_date_release()

  for _,i in pairs({"Class", "File", "Package"}) do
    if string.match(
      line,
      "^\\ProvidesExpl" .. i .. " *{[a-zA-Z0-9%-%.]+}"
    ) then
      line = string.gsub(
        line,
        "{%d%d%d%d/%d%d/%d%d}( *){[^}]*}",
        "{" .. string.gsub(date, "%-", "/") .. "}%1{" .. release .. "}"
      )
      break
    end
  end
  return line
end

--###  doc_init_hook begin  ############################################
--[[
  The git informations (commit name, commit date, commit author)
  must be included in the .sty files. This is done here.
  1. git describe --long HEAD: returns the most recent tag (HEAD
       can be omitted, it's the default), that's the commit name
  2. git --no-pager show -s --format=format:"<format>": returns
       the needed commit date and commit author. <format> is set
       up so that the three lines below are generated

  These informations replace the line
  %% git revision information
  by someting like
  \@git@ $Date: <commit date> $%
     $Revision: <commit name> $
  %% $Author: <commit author> $

  <commit date> has the format "yyyy-mm-dd hh:mm:ss +nnnn"
  <commit name> has the format as described in the git describe
    man page
--]]
function docinit_hook()
  print("now set git data")
  local f = io.popen('git describe --long HEAD', 'r')
  local commit_name = f:read "*all"
  commit_name = string.sub(commit_name, 1, #commit_name - 1)

  f = io.popen('git --no-pager show -s --format=format:"%n  ' ..
                 '\\@git@ \\$Date: %ci \\$%%%%%n  \\$Revision: ' ..
                 '<commit name> \\$%n  %%%%%%%% \\$Author: %cn \\$%n"')
  local revision_information = f:read "*all"
  revision_information = string.sub(revision_information, 1,
      #revision_information - 1)

  print("commit_name: >>" .. commit_name .. "<<, Länge: " ..
      tostring(string.len(commit_name)))
  print("revision_information: " .. revision_information)

  revision_information = revision_information:gsub("<commit name>", commit_name)
  print("revision_information: " .. revision_information)

  filenames = {"strukdoc.sty", "struktex.sty", "struktxf.sty", "struktxp.sty"}

  for _, file in ipairs(filenames) do
    file = unpackdir .. "/" .. file
    print(file)

    local f = assert(io.open(file,"rb"))
    local content = f:read("*all")
    f:close()

    content = content:gsub("%%%% git revision information",
                           revision_information)
    print(content)

    f = assert(io.open(file,"w"))
    f:write(content)
    f:close()

    if file == unpackdir .."/" .. "struktex.sty" then
      file = file:gsub(unpackdir, typesetdir)
      f = assert(io.open(file,"w"))
      f:write(content)
      f:close()
    end
  end

  -- this file is needed for the documentation but isn't automatically
  -- copied
  cp("struktex-tst-00.nss", unpackdir, typesetdir)

  return 0
end
--###  doc_init_hook end  ##############################################

-- Find and run the build system
kpse.set_program_name("kpsewhich")
if not release_date then
  dofile(kpse.lookup("l3build.lua"))
end


