#!/opt/lnxall_app/bin/lua

local invoker = require "invoker"

local BR_DIR = "/sys/class/backlight/backlight1"

local function write_brightness(file, value)
	local fpath = string.format("%s/%s", BR_DIR, file)
	local filp = io.open(fpath, "wb")
	if filp then
		filp:write(value)
		filp:close()
		filp = nil
		return true
	end

	io.stderr:write(string.format("Error, cannot open '%s'\n", fpath))
	io.stderr:flush()
	return false
end

local bval = arg[1]
if type(bval) ~= "string" then
	local bval = invoker.readfile(BR_DIR .. "/brightness", invoker.TRIMEND)
	if bval then
		io.stdout:write(string.format("Current brightness value: %s\n", bval))
		io.stdout:flush()
		os.exit(0)
	end

	io.stderr:write("Error, failed to read current brightness value.\n")
	io.stderr:flush()
	os.exit(1)
end

bval = tonumber(bval)
if type(bval) ~= "number" or bval ~= math.floor(bval) or bval < 0 or bval > 255 then
	io.stderr:write(string.format("Error, invalid brightness value: %s\n", arg[1]))
	io.stderr:flush()
	os.exit(2)
end

if bval == 0 then
	write_brightness("bl_power", "1\n")
	write_brightness("brightness", "0\n")
	os.exit(0)
end

write_brightness("bl_power", "1\n")
invoker.msleep(20)
write_brightness("bl_power", "0\n")
write_brightness("brightness", string.format("%d\n", bval))
os.exit(0)
