#!/usr/pkg/bin/texlua
-- Package tex4ebook. Author Michal Hoftich <michal.h21@gmail.com>
-- This package is subject of LPPL license, version 1.3 
--
kpse.set_program_name("luatex")
require("lapp-mk4")
-- require("ebookutils")
logging = require "make4ht-logging"
if os.type == "windows" then logging.use_colors = false end
local log = logging.new("tex4ebook")
local ebookutils = require "mkutils"
local mkparams = require "mkparams"
local mk_config = require "make4ht-config"

-- Setting
local latex_cmd="latex"
local copy_cmd="copy"
local move_cmd="move"
local env_param="%%" 
local htlatex_call=""
-- These correspond to htlatex parameters
local tex4ht_sty_par=""
local tex4ht_par=""
local t4ht_par=""
local latex_par=""
local output_formats={epub=true,mobi=true,epub3=true,azw=true, azw3=true}
local executor=nil
local tidy = false
local include_fonts = false

-- message used for option parsing by the mkparams lib
local arg_message = [[
tex4ebook - ebook generation support for LaTeX
Usage:
tex4ebook [switches] filename ["tex4ht.sty op."] ["tex4ht op."] ["t4ht op"] ["latex op"]
  -a,--loglevel (default status) Set log level.
                possible values: debug, info, status, warning, error, fatal
  -c,--config (default xhtml) Custom config file
  -d,--output-dir (default nil)  Output directory
  -B,--build-dir (default nil)  Build directory
  -e,--build-file (default nil)  If build file is different than `filename`.mk4
  -f,--format (default epub) Output format. Supported values: epub, epub3, mobi
  -h,--help  Display help message
  -j,--jobname (default nil)  Set the jobname
  -l,--lua  Use lualatex for document compilation
  -m,--mode (default default) Switch which can be used in the makefile
  -r,--resolution (default nil)  This option is obsolete, use build files instead!
  -s,--shell-escape  Enable shell escape in htlatex run
  -t,--tidy Run html tidy on html output. May result in wrong spacing!
  -x,--xetex Use xelatex for document compilation
  -v,--version  Display version number
  ]]
  
-- options for the template used by mkparams to generate the help message
local mkparams_parameters = {
  progname = "tex4ebook",
  issue_tracker = "https://github.com/michal-h21/tex4ebook/issues"
}

-- process the command line arguments
local args = mkparams.get_args(mkparams_parameters, arg_message)

if args["filename"] == nil and args["version"] == false then
  print(arg_message) 
  return
else
  input_file=args["filename"]
end

if args.version then
  print "tex4ebook v0.4"
  return 
end

if args.lua then
  latex_cmd="dvilualatex"
elseif args.xetex then
  latex_cmd="xelatex --no-pdf"
end


if args["shell-escape"] then 
  latex_par = latex_par .. " -shell-escape"
end

if args["include-fonts"] then 
  include_fonts = true
end

local   mode = args.mode or "default"

if os.type=="unix" then
  env_param="$"
  copy_cmd="cp"
  move_cmd="mv"
  t4ht_dir_format="%s/"
else 
  env_param="%%"
  copy_cmd="copy"
  move_cmd="move"
  t4ht_dir_format="%s"
end

if args.tidy then 
  tidy = true
else
  tidy = false
end

local sty_args = ""
if args[2] then 
  sty_args = "," .. args[2]
end
local tex4ht_sty_par = tex4ht_sty_par + sty_args --args[2]
local tex4ht_par = tex4ht_par +args[3]
local t4ht_par = t4ht_par + args[4]
local latex_par = latex_par + args[5]

-- use default parameter processing from make4ht
-- add some needed args (is it useful anymore?)
args.filename=input_file

-- let make4ht handle the common options
local params = mkparams.process_args(args)
local input = params.input
log:status("Conversion started")
log:status("Input file: ".. params.tex_file)

if params.builddir ~= "" then
  mkutils.make_path(params.builddir)
end



local output_format = params.output_format 
-- use epub as default output_format
output_format = output_format or "epub"
-- load common_domfilters extension by default
local extensions = ebookutils.add_extensions("+common_domfilters", params.extensions)
extensions = ebookutils.load_extensions(extensions, output_format)
-- but also support tex4ebook!s own parameters
local oldparams = {
  -- htlatex=latex_cmd
  -- ,input=input 
  -- ,tex_file = tex_file
  format = output_format
  -- ,latex_par=latex_par
  -- ,tex4ht_sty_par=tex4ht_sty_par
  -- ,tex4ht_par=tex4ht_par
  -- ,t4ht_par=t4ht_par
  -- ,mode = mode
  ,t4ht_dir_format=t4ht_dir_format
  ,tidy = tidy
  ,include_fonts = include_fonts
  ,resolution=args.resolution
  ,packages="\\RequirePackage{tex4ebook}"
}  

if oldparams.resolution~="nil" then
  log:warning("The resolution parameter is deprecated. Please use a build file")
  log:warning("See information about Make:image() command in Make4ht documenation")
end

-- extend params
for k,v in pairs(oldparams) do
  params[k] = v
end

params.tex4ht_sty_par=params.tex4ht_sty_par .. ",charset=utf-8,"..output_format
params.tex4ht_par= " -cmozhtf -utf8" .. params.tex4ht_par



-- find tex4ebook configuration file
local configname = "tex4ebook"
local conffile = mk_config.find_config(configname) or mk_config.find_xdg_config(configname)
if conffile then
  log:info("Using configuration file: " .. conffile)
  ebookutils.load_config(params, conffile)
else
  log:info "No conffile"
end

local build_file = input.. ".mk4"

if args["build-file"] and args["build-file"] ~= "nil"  then 
	build_file = args["build-file"] 
end

local config_file = ebookutils.load_config(params, build_file)

params["config_file"] = config_file


if output_formats[output_format] then
  executor=require("tex4ebook-exec_"..output_format)
  params=executor.prepare(params)
  if #extensions > 0 then
    params = ebookutils.extensions_prepare_parameters(extensions,params)
  end
else
  log:error("Unknown output format: "..output_format)
  return
end
--config_file.Make:run()
-- print("${htlatex} ${input} \"${tex4ht_sty_par}\" \"${tex4ht_par}\" \"${t4ht_par}\" \"${latex_par}\"" % params)
if #extensions > 0 then
  config_file.Make = ebookutils.extensions_modify_build(extensions, config_file.Make)
end

executor.run(input,params)
executor.writeContainer()
executor.clean()
log:status("Conversion finished")
logging.exit_status()
--print(args[1])
