#! /usr/bin/lua

local nixio = require("nixio")
local sys = require("luci.sys")

function execute(args)
    local result = { changed = false, failed = false }

    local pid = nixio.fork()
    if pid == -1 then
        result.failed = true
    elseif pid == 0 then
        nixio.setsid() -- Stop ansible killing the child on the way out
        sys.reboot()
    else
        result.changed = true
        result.msg = "Rebooting"
    end

    return result
end

-- Boilerplate below --

local json = require("luci.jsonc")

local success, result = pcall(execute, json.parse([[<<INCLUDE_ANSIBLE_MODULE_JSON_ARGS>>]]))
if not success then
    result = {
        failed = true,
        changed = false,
        msg = result
    }
else
    if result.failed ~= false then
        result.failed = true
    end
    if result.changed ~= false then
        result.changed = true
    end
end
io.write(json.stringify(result))
