-- Run this explicitly through -*- Lua -*-

-- Copyright 2012-2017 Daniel Silverstone <dsilvers@digital-scurf.org>
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
-- 1. Redistributions of source code must retain the above copyright
--    notice, this list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright
--    notice, this list of conditions and the following disclaimer in the
--    documentation and/or other materials provided with the distribution.
-- 3. Neither the name of the author nor the names of their contributors
--    may be used to endorse or promote products derived from this software
--    without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
-- OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.

local lua_bin, inst_share_path, inst_bin_path, inst_mod_path, inst_plugin_path, input_name, output_name, coverage_path, report_path = ...

local input_fh = assert(io.open(input_name, "r"))
local output_fh = assert(io.open(output_name, "w"))

local line = input_fh:read "*l"

if not inst_mod_path:match("%?") then
   inst_mod_path = inst_mod_path .. "/?.lua"
   inst_mod_path = inst_mod_path:gsub("/+", "/")
end

if coverage_path and coverage_path == "" then
   coverage_path = nil
end

if coverage_path and not coverage_path:match("%?") then
   coverage_path = coverage_path .. "/?.lua"
   coverage_path = coverage_path:gsub("/+", "/")
end

local coverage_part
if coverage_path then
   -- We are generating coverage, the part is the leafname of the
   -- output binary
   coverage_part = output_name:gsub("^.+/", "")
end

local mod_path_present = false
for path_elem in package.path:gmatch("([^;]+)") do
   if path_elem == inst_mod_path then
      mod_path_present = true
      break
   end
end

do
   -- transform the plugin path from colon separated to a table
   -- for interpolation
   local path = {}
   for entry in string.gmatch(inst_plugin_path, "([^:]+)") do
      path[#path+1] = ("%q"):format(entry)
   end
   inst_plugin_path = ("{%s}"):format(table.concat(path, ", "))
end

while line do
   local token = line:match("^%-%- @@(.+)$")
   if token then
      if token == "SHEBANG" then
         output_fh:write(("#!%s\n"):format(lua_bin))
      elseif token == "GITANO_LUA_PATH" then
         if not mod_path_present then
            output_fh:write(("package.path = ('%%s;%%s'):" ..
                                "format(%q, package.path)"
                            ):format(inst_mod_path))
         else
            output_fh:write("--[[Gitano modules installed into " ..
                               inst_mod_path .. "]]")
         end
         if coverage_path then
            output_fh:write((" package.path = ('%%s;%%s'):" ..
                                "format(%q, package.path)"
                            ):format(coverage_path))
            output_fh:write((" require('gitano.coverage').begin(%q, %q)"
                            ):format(report_path, coverage_part))
         end
         output_fh:write("\n")
      elseif token == "GITANO_BIN_PATH" then
         output_fh:write(("gitano.config.lib_bin_path(%q)\n"):format(inst_bin_path))
      elseif token == "GITANO_SHARE_PATH" then
         output_fh:write(("gitano.config.share_path(%q)\n"):format(inst_share_path))
      elseif token == "GITANO_PLUGIN_PATH" then
         output_fh:write(("gitano.plugins.load_plugins %s\n"):format(inst_plugin_path))
      elseif token == "GITANO_I18N_PATH" then
         output_fh:write(("gitano.i18n.set_langpack_path(%q) gitano.i18n.set_category()\n"):format(inst_share_path .. "/lang"))
      else
         output_fh:write("-- Unknown token: " .. token .. "\n")
      end
   elseif line:match("@@%.luacov@@") then
      local handle = io.popen('pwd')
      local cwd = handle:read("*all"):sub(0, -2)
      output_fh:write(line:gsub("@@%.luacov@@", cwd .. "/.luacov") .. "\n")
      handle:close()
   else
      output_fh:write(line .. "\n")
   end
   line = input_fh:read "*l"
end
