#! /usr/bin/env lua
-- vim:sw=4:sts=4
-- Configure all modules of LuaGnome.
-- Pass extra arguments to all modules.

require "lfs"

function parse_cmdline()
    local s, last_opt, modules

    -- from the last option forward, detect modules
    last_opt = #arg
    for i = #arg, 1, -1 do
	s = arg[i]
	if lfs.attributes("src/" .. s .. "/spec.lua", "mode") ~= "file" then
	    break
	end
	last_opt = i - 1
    end

    modules = { unpack(arg, last_opt + 1) }

    if #modules == 0 then
	for mod in lfs.dir"src" do
	    if string.sub(mod, 1, 1) ~= "." and
		lfs.attributes("src/" .. mod, "mode") == "directory"
		and lfs.attributes("src/"..mod.."/spec.lua", "mode") == "file"
		then
		modules[#modules + 1] = mod
	    end
	end
    end

    -- The "gnome" module must be configured first.
    for i, name in ipairs(modules) do
	if name == "gnome" and i > 1 then
	    table.insert(modules, 1, table.remove(modules, i))
	    break
	end
    end

    return last_opt, modules
end


---
-- Run the configure script for each module.
-- @return  true on success, false on error
--
function run_sub_configure(last_opt, modules)
    local cmd, n, rc

    cmd = { "script/configure.lua", unpack(arg, 1, last_opt) }
    n = #cmd + 1
    for _, mod in ipairs(modules) do
	cmd[n] = mod
	rc = os.execute(table.concat(cmd, " "))
	-- stop on fatal error, or when --help was used.
	if rc >= 10 * 256 then
	    return false
	end
    end

    return true
end

function main()
    local last_opt, modules = parse_cmdline()
    if run_sub_configure(last_opt, modules) then
	print'Type "make" to build all modules.  On multi-core or '
	print'multi-processor machines, try "make -j"'
    end
end

main()

