#!/opt/lnxall_app/bin/lua

-- Created by jiaqiang.ye@lnxall.com
-- Simple waitlock implementation for command invoking
-- 2026/04/30

local invoker = require "invoker"

local function mainfunc()
	local args = {}
	local lockfile = "/tmp/.netuci-lock"

	local i, j = 1, 0
	if arg[i] == "-f" then
		i = i + 1
		lockfile = arg[i]
		if type(lockfile) ~= "string" or #lockfile == 0 then
			io.stderr:write("Error, lockfile not specified.\n")
			io.stderr:flush()
		else
			i = i + 1
		end
	end

	while arg[i] do
		j = j + 1
		args[j] = arg[i]
		i = i + 1
	end
	if j == 0 then
		io.stderr:write("Error, no arguments specified.\n")
		io.stderr:flush()
		os.exit(0)
	end

	local lockfd = invoker.waitlock(lockfile)
	if lockfd then invoker.cloexec(lockfd, true) end
	-- io.stdout:write(string.format("Invoking command: %s\n", table.concat(args, " ")))
	-- io.stdout:flush()
	local okay = invoker.invoke(0, args)
	if type(okay) ~= "number" then okay = 1 end
	os.exit(okay)
end

mainfunc()
