-- FactoryOS startup — put this file at computer root alongside factoryos/.
-- Reads /factoryos/node.cfg for `role`, runs the matching role program.

package.path = "/?.lua;/?/init.lua;" .. package.path

-- first boot: interactive setup wizard (or boot unclaimed for remote
-- adoption). setup reboots itself when it writes a cfg.
if not fs.exists("/factoryos/node.cfg")
  and fs.exists("/factoryos/programs/setup.lua") then
  pcall(dofile, "/factoryos/programs/setup.lua")
end

local role = "controller"
if fs.exists("/factoryos/node.cfg") then
  local h = fs.open("/factoryos/node.cfg", "r")
  local src = h.readAll(); h.close()
  local fn = load(src, "node.cfg", "t", {})
  local ok, c = pcall(fn)
  if ok and type(c) == "table" and c.role then role = c.role end
end

local prog = "/factoryos/programs/" .. role .. ".lua"
if not fs.exists(prog) then
  print("factoryos: no program for role '" .. role .. "'")
  return
end

local ok, err = pcall(dofile, prog)
if not ok then
  print("factoryos " .. role .. " crashed:")
  print(err)
end
