April_The_Sergal

CC:Networking installation script

Sep 27th, 2025 (edited)
264
0
Never
8
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 26.02 KB | Gaming | 0 0
  1. -- install.lua
  2. -- ComputerCraft Network System Installer (Stage 1)
  3. -- Reboot-gated safe install:
  4. --   - Reads netinst.cfg.start_background_processes
  5. --   - If true, set false and reboot so startup.lua won't spawn daemons
  6. --   - After reboot (flag=false), set true again and run GUI installer
  7. -- Also:
  8. --   - Ensures netinst.cfg exists with sane defaults (including blacklist)
  9. --   - (Re)installs Basalt per policy: "always" | "never" | "ask"
  10. --   - Generates install_network.lua (Basalt v2-friendly) and runs it
  11.  
  12. local CONFIG_PATH = "netinst.cfg"
  13.  
  14. local DEFAULT_CFG = [[
  15. -- netinst.cfg
  16. -- Network installer configuration (Lua table).
  17. return {
  18.   -- Files or directories to ignore (never deleted or overwritten).
  19.   -- Matches by prefix, e.g. "logs" ignores "logs/..." as well.
  20.   blacklist = {
  21.     "cleanup.lua",
  22.     "logs",
  23.     "netinst.cfg",   -- protect the config itself
  24.     "basalt.lua"     -- don't overwrite Basalt during file copy
  25.   },
  26.  
  27.   -- Where to write installer logs (created if missing). Set to nil to disable file logging.
  28.   log_file = "logs/installer.log",
  29.  
  30.   -- How many retries for a failed download (1..3)
  31.   retries = 2,
  32.  
  33.   -- Install mode for files:
  34.   --   "ask"   -> dialog (clean/update/cancel)
  35.   --   "clean" -> clean install automatically (respects blacklist)
  36.   --   "update"-> update/overwrite automatically (respects blacklist)
  37.   install_mode = "ask",
  38.  
  39.   -- Basalt reinstall policy for Stage-1:
  40.   --   "always" (default first-run behavior), "never", or "ask"
  41.   reinstall_basalt = "always",
  42.  
  43.   -- First-run flag. On the first GUI run, you'll be asked for your preferred
  44.   -- reinstall_basalt policy; the installer will set hasInstalled=true afterward.
  45.   hasInstalled = false,
  46.  
  47.   -- Handshake with startup.lua. When false, startup.lua will not start daemons
  48.   -- and will chain into install.lua. This script flips it back to true on entry.
  49.   start_background_processes = true,
  50.  
  51.   -- Optional: cooperative process cleanup inside the GUI (usually not needed
  52.   -- after the reboot gate, but harmless to keep)
  53.   kill_processes = true,
  54. }
  55. ]]
  56.  
  57. -- ===== small utilities =====
  58. local function printColored(text, color)
  59.   local old = term.getTextColor and term.getTextColor() or colors.white
  60.   if term.isColor and term.isColor() and color then term.setTextColor(color) end
  61.   print(text)
  62.   if term.isColor and term.isColor() then term.setTextColor(old) end
  63. end
  64.  
  65. local function ensureConfig()
  66.   if not fs.exists(CONFIG_PATH) then
  67.     local dir = fs.getDir(CONFIG_PATH)
  68.     if dir ~= "" and not fs.exists(dir) then fs.makeDir(dir) end
  69.     local f = fs.open(CONFIG_PATH, "w"); f.write(DEFAULT_CFG); f.close()
  70.   end
  71. end
  72.  
  73. local function loadConfig()
  74.   ensureConfig()
  75.   local fn = loadfile(CONFIG_PATH, nil, {})
  76.   local ok, cfg = pcall(fn or function() end)
  77.   if not ok or type(cfg) ~= "table" then
  78.     cfg = (load(DEFAULT_CFG, "cfg", "t", {}))()
  79.   end
  80.   -- sanitize
  81.   cfg.retries = math.max(1, math.min(3, tonumber(cfg.retries or 2) or 2))
  82.   if type(cfg.blacklist) ~= "table" then cfg.blacklist = {} end
  83.   if cfg.reinstall_basalt ~= "always" and cfg.reinstall_basalt ~= "never" and cfg.reinstall_basalt ~= "ask" then
  84.     cfg.reinstall_basalt = "always"
  85.   end
  86.   if cfg.install_mode ~= "clean" and cfg.install_mode ~= "update" then
  87.     cfg.install_mode = "ask"
  88.   end
  89.   if cfg.hasInstalled ~= true then cfg.hasInstalled = false end
  90.   if cfg.start_background_processes == nil then cfg.start_background_processes = true end
  91.   if cfg.kill_processes == nil then cfg.kill_processes = true end
  92.   return cfg
  93. end
  94.  
  95. local function saveConfig(cfg)
  96.   local function q(s) return string.format("%q", s) end
  97.   local t = {}
  98.   table.insert(t, "return {")
  99.   table.insert(t, "  blacklist = {")
  100.   for _,p in ipairs(cfg.blacklist or {}) do table.insert(t, "    " .. q(p) .. ",") end
  101.   table.insert(t, "  },")
  102.   table.insert(t, "  log_file = " .. (cfg.log_file and q(cfg.log_file) or "nil") .. ",")
  103.   table.insert(t, "  retries = " .. tostring(math.max(1, math.min(3, tonumber(cfg.retries or 2) or 2))) .. ",")
  104.   table.insert(t, "  install_mode = " .. q(cfg.install_mode or "ask") .. ",")
  105.   table.insert(t, "  reinstall_basalt = " .. q(cfg.reinstall_basalt or "always") .. ",")
  106.   table.insert(t, "  hasInstalled = " .. tostring(cfg.hasInstalled and true or false) .. ",")
  107.   table.insert(t, "  start_background_processes = " .. tostring(cfg.start_background_processes ~= false) .. ",")
  108.   table.insert(t, "  kill_processes = " .. tostring(cfg.kill_processes ~= false) .. ",")
  109.   table.insert(t, "}")
  110.   local dir = fs.getDir(CONFIG_PATH)
  111.   if dir ~= "" and not fs.exists(dir) then fs.makeDir(dir) end
  112.   local f = fs.open(CONFIG_PATH, "w"); f.write(table.concat(t, "\n")); f.close()
  113. end
  114.  
  115. -- ===== check internet (event-based, no hang) =====
  116. local function checkInternet(timeout_s)
  117.   local url = "https://www.google.com"
  118.   if http.checkURL and http.checkURL(url) == false then return false end
  119.   local tid = os.startTimer(timeout_s or 3)
  120.   http.request(url)
  121.   while true do
  122.     local ev, a = os.pullEvent()
  123.     if ev == "http_success" then
  124.       local h = a; if h and h.close then h.close() end
  125.       return true
  126.     elseif ev == "http_failure" then
  127.       return false
  128.     elseif ev == "timer" and a == tid then
  129.       return false
  130.     end
  131.   end
  132. end
  133.  
  134. -- ===== Basalt policy =====
  135. local function installBasalt()
  136.   print("Installing Basalt GUI framework...")
  137.   local ok = shell.run("wget", "run", "https://raw.githubusercontent.com/Pyroxenium/Basalt2/main/install.lua")
  138.   if not ok then printColored("ERROR: Failed to install Basalt", colors.red); return false end
  139.   printColored("Basalt installed successfully", colors.green)
  140.   return true
  141. end
  142.  
  143. local function promptYesNo(msg, defaultNo)
  144.   io.write(msg .. (defaultNo and " [y/N] " or " [Y/n] "))
  145.   local ans = (read() or ""):lower():gsub("^%s+",""):gsub("%s+$","")
  146.   if ans == "" then return not defaultNo end
  147.   return (ans == "y" or ans == "yes")
  148. end
  149.  
  150. local function handleBasaltPolicy(cfg)
  151.   local policy = cfg.reinstall_basalt or "always"
  152.   local exists = fs.exists("basalt.lua")
  153.   if policy == "always" then
  154.     return installBasalt()
  155.   elseif policy == "never" then
  156.     if exists then print("Basalt present (policy=never), skipping reinstall"); return true
  157.     else print("Basalt missing (policy=never), installing once"); return installBasalt() end
  158.   else
  159.     local doInstall = promptYesNo("Reinstall Basalt now?", true)
  160.     if doInstall then return installBasalt() end
  161.     print("Skipping Basalt reinstall (asked)")
  162.     if not exists then print("Basalt not present; installing required dependency anyway"); return installBasalt() end
  163.     return true
  164.   end
  165. end
  166.  
  167. -- ===== write the Basalt GUI installer (v2-friendly) =====
  168. local function writeGUIInstaller()
  169.   local code = [=[
  170. -- install_network.lua
  171. -- Basalt GUI installer (safe reboot gate already done by stage-1)
  172. local basalt = require("basalt")
  173.  
  174. -- ===== Config I/O =====
  175. local CONFIG_PATH = "netinst.cfg"
  176.  
  177. local function loadConfig()
  178.   local fn = loadfile(CONFIG_PATH, nil, {})
  179.   if not fn then return {} end
  180.   local ok, cfg = pcall(fn)
  181.   if not ok or type(cfg) ~= "table" then return {} end
  182.   cfg.retries = math.max(1, math.min(3, tonumber(cfg.retries or 2) or 2))
  183.   if type(cfg.blacklist) ~= "table" then cfg.blacklist = {} end
  184.   if cfg.reinstall_basalt ~= "always" and cfg.reinstall_basalt ~= "never" and cfg.reinstall_basalt ~= "ask" then
  185.     cfg.reinstall_basalt = "always"
  186.   end
  187.   cfg.install_mode = (cfg.install_mode == "clean" or cfg.install_mode == "update") and cfg.install_mode or "ask"
  188.   if cfg.hasInstalled ~= true then cfg.hasInstalled = false end
  189.   if cfg.start_background_processes == nil then cfg.start_background_processes = true end
  190.   if cfg.kill_processes == nil then cfg.kill_processes = true end
  191.   return cfg
  192. end
  193.  
  194. local function saveConfig(cfg)
  195.   local function q(s) return string.format("%q", s) end
  196.   local t = {}
  197.   table.insert(t, "return {")
  198.   table.insert(t, "  blacklist = {")
  199.   for _,p in ipairs(cfg.blacklist or {}) do table.insert(t, "    " .. q(p) .. ",") end
  200.   table.insert(t, "  },")
  201.   table.insert(t, "  log_file = " .. (cfg.log_file and q(cfg.log_file) or "nil") .. ",")
  202.   table.insert(t, "  retries = " .. tostring(math.max(1, math.min(3, tonumber(cfg.retries or 2) or 2))) .. ",")
  203.   table.insert(t, "  install_mode = " .. q(cfg.install_mode or "ask") .. ",")
  204.   table.insert(t, "  reinstall_basalt = " .. q(cfg.reinstall_basalt or "always") .. ",")
  205.   table.insert(t, "  hasInstalled = " .. tostring(cfg.hasInstalled and true or false) .. ",")
  206.   table.insert(t, "  start_background_processes = " .. tostring(cfg.start_background_processes ~= false) .. ",")
  207.   table.insert(t, "  kill_processes = " .. tostring(cfg.kill_processes ~= false) .. ",")
  208.   table.insert(t, "}")
  209.   local d = fs.getDir(CONFIG_PATH)
  210.   if d ~= "" and not fs.exists(d) then fs.makeDir(d) end
  211.   local f = fs.open(CONFIG_PATH, "w"); f.write(table.concat(t, "\n")); f.close()
  212. end
  213.  
  214. local CFG = loadConfig()
  215.  
  216. -- ===== repo & files =====
  217. local GITHUB_REPO = "https://raw.githubusercontent.com/Temperdox/CC_Networking/master/src"
  218. local FILE_MAP = {
  219.   ["startup.lua"]="startup.lua",
  220.   ["router_startup.lua"]="router_startup.lua",
  221.   ["wifi_client.lua"]="wifi_client.lua",
  222.   ["dhcp_client.lua"]="dhcp_client.lua",
  223.   ["firewall_manager.lua"]="firewall_manager.lua",
  224.   ["router_monitor.lua"]="router_monitor.lua",
  225.   ["network_demo.lua"]="network_demo.lua",
  226.   ["user_startup.lua"]="user_startup.lua",
  227.   ["test_server.lua"]="test_server.lua",
  228.   ["test_network.lua"]="test_network.lua",
  229.   ["tests/test_websocket.lua"]="tests/test_websocket.lua",
  230.   ["tests/test_http.lua"]="tests/test_http.lua",
  231.   ["tests/test_tcp.lua"]="tests/test_tcp.lua",
  232.   ["tests/test_udp.lua"]="tests/test_udp.lua",
  233.   ["tests/test_https.lua"]="tests/test_https.lua",
  234.   ["tests/test_webrtc.lua"]="tests/test_webrtc.lua",
  235.   ["tests/test_mqtt.lua"]="tests/test_mqtt.lua",
  236.   ["tests/test_ftp.lua"]="tests/test_ftp.lua",
  237.   ["tests/test_ssh.lua"]="tests/test_ssh.lua",
  238.   ["tests/test_client.lua"]="tests/test_client.lua",
  239.   ["tests/servers/http_test_server.lua"]="tests/servers/http_test_server.lua",
  240.   ["tests/servers/udp_server.lua"]="tests/servers/udp_server.lua",
  241.   ["tests/servers/websocket_server.lua"]="tests/servers/websocket_server.lua",
  242.   ["tests/servers/launcher.lua"]="tests/servers/launcher.lua",
  243.   ["hardware_watchdog.lua"]="hardware_watchdog.lua",
  244.   ["cleanup.lua"]="cleanup.lua",
  245.  
  246.   ["bin/netd.lua"]="bin/netd.lua",
  247.   ["bin/routerd.lua"]="bin/routerd.lua",
  248.   ["lib/network.lua"]="lib/network.lua",
  249.  
  250.   ["etc/network.cfg"]="config/network.cfg",
  251.   ["etc/router.cfg"]="config/router.cfg",
  252.   ["etc/wireless.cfg"]="config/wireless.cfg",
  253.   ["etc/wifi.cfg"]="config/wifi.cfg",
  254.   ["config/network.cfg"]="config/network.cfg",
  255.  
  256.   ["protocols/protocol_names.lua"]="protocols/protocol_names.lua",
  257.   ["protocols/statuses.lua"]="protocols/statuses.lua",
  258.   ["protocols/network_adapter.lua"]="protocols/network_adapter.lua",
  259.   ["protocols/websocket.lua"]="protocols/websocket.lua",
  260.   ["protocols/http_client.lua"]="protocols/http_client.lua",
  261.   ["protocols/tcp.lua"]="protocols/tcp.lua",
  262.   ["protocols/udp.lua"]="protocols/udp.lua",
  263.   ["protocols/mqtt.lua"]="protocols/mqtt.lua",
  264.   ["protocols/ftp.lua"]="protocols/ftp.lua",
  265.   ["protocols/ssh.lua"]="protocols/ssh.lua",
  266.   ["protocols/webrtc.lua"]="protocols/webrtc.lua",
  267.  
  268.   ["util/logger.lua"]="util/logger.lua",
  269.   ["util/connection_manager.lua"]="util/connection_manager.lua",
  270.  
  271.   ["usr/lib/router/install.lua"]="usr/lib/router/install.lua",
  272.   ["usr/lib/router/routerd.lua"]="usr/lib/router/routerd.lua",
  273.   ["usr/lib/router/web_admin.lua"]="usr/lib/router/web_admin.lua",
  274.   ["usr/lib/router/qos.lua"]="usr/lib/router/qos.lua",
  275. }
  276. local DIRECTORIES = {
  277.   "bin","lib","etc","config","protocols","util","tests",
  278.   "usr","usr/lib","usr/lib/router",
  279.   "var","var/run","var/lib","var/lib/dhcp","var/log","var/cache",
  280.   "logs"
  281. }
  282.  
  283. local function isBlacklisted(path)
  284.   for _,p in ipairs(CFG.blacklist or {}) do
  285.     if path == p or path:sub(1, #p + 1) == p .. "/" then return true end
  286.   end
  287.   return false
  288. end
  289.  
  290. -- ===== logging =====
  291. local logFileHandle=nil
  292. local function logInit()
  293.   if CFG.log_file then
  294.     local d=fs.getDir(CFG.log_file); if d~="" and not fs.exists(d) then fs.makeDir(d) end
  295.     logFileHandle=fs.open(CFG.log_file,"a")
  296.     if logFileHandle then logFileHandle.write(("[%s] --- installer start ---\n"):format(os.date("%H:%M:%S"))); logFileHandle.flush() end
  297.   end
  298. end
  299. local function logClose()
  300.   if logFileHandle then logFileHandle.write(("[%s] --- installer end ---\n"):format(os.date("%H:%M:%S"))); logFileHandle.close() end
  301. end
  302. local function logWriteGUI(listWidget, msg, color)
  303.   local entry = ("[%s] %s"):format(os.date("%H:%M:%S"), msg)
  304.   if listWidget then
  305.     listWidget:addItem(entry, color or colors.white, colors.black)
  306.     if listWidget.scrollToBottom then listWidget:scrollToBottom() end
  307.   end
  308.   if logFileHandle then logFileHandle.write(entry.."\n"); logFileHandle.flush() end
  309. end
  310.  
  311. local function termSize() local w,h=term.getSize(); return w,h end
  312.  
  313. -- ===== state =====
  314. local state = { current_file="", progress=0, total_files=0, success_count=0, failed_files={}, skipped_blacklisted={} }
  315.  
  316. -- ===== GUI =====
  317. local main, statusLabel, progressLabel, progressBar, logList
  318. local function removeElement(el)
  319.   if not el then return end
  320.   if el.remove then
  321.     el:remove()
  322.     return
  323.   end
  324.   local parent = (el.getParent and el:getParent()) or main
  325.   if parent and parent.removeChild then
  326.     parent:removeChild(el)
  327.   elseif el.setVisible then
  328.     el:setVisible(false)
  329.   end
  330. end
  331.  
  332. local function createGUI()
  333.   local w,h=termSize()
  334.   main=basalt.getMainFrame():setBackground(colors.blue):setSize(w,h)
  335.   main:addLabel():setPosition(1,1):setSize(w,1):setText("ComputerCraft Network System Installer")
  336.       :setForeground(colors.white):setBackground(colors.blue)
  337.   local statusPanel=main:addFrame():setPosition(2,3):setSize(w-2,8):setBackground(colors.white)
  338.   statusPanel:addLabel():setPosition(1,1):setText("Installation Status"):setForeground(colors.black)
  339.   statusLabel=statusPanel:addLabel():setPosition(1,3):setText("Initializing..."):setForeground(colors.gray)
  340.   progressLabel=statusPanel:addLabel():setPosition(1,5):setText("0 / 0 files"):setForeground(colors.gray)
  341.   progressBar=statusPanel:addProgressBar():setPosition(1,6):setSize(w-2,1)
  342.       :setBackground(colors.lightGray):setProgressColor(colors.lime):setProgress(0)
  343.   local logPanel=main:addFrame():setPosition(2,12):setSize(w-2,8):setBackground(colors.black)
  344.   logPanel:addLabel():setPosition(1,1):setText("Installation Log"):setForeground(colors.white)
  345.   logList=logPanel:addList():setPosition(1,2):setSize(w-2,6):setBackground(colors.black):setForeground(colors.white)
  346. end
  347.  
  348. local function addLog(msg, level)
  349.   local color = colors.white
  350.   if level == "ERROR" then color = colors.red
  351.   elseif level == "SUCCESS" then color = colors.lime
  352.   elseif level == "WARNING" then color = colors.yellow end
  353.   logWriteGUI(logList, msg, color)
  354. end
  355.  
  356. local function updateProgress()
  357.   local pct=0; if state.total_files>0 then pct=math.floor((state.progress/state.total_files)*100) end
  358.   progressLabel:setText(("%d / %d (%d%%)"):format(state.progress,state.total_files,pct))
  359.   progressBar:setProgress(pct)
  360.   if state.current_file~="" then statusLabel:setText("Installing: "..state.current_file) end
  361. end
  362.  
  363. -- first-run policy
  364. local function firstRunPolicyDialog()
  365.   local w,h=termSize()
  366.   local dw=math.max(34, math.floor(w*3/4)); if dw>w-2 then dw=w-2 end
  367.   local dh=12; local dx,dy=math.floor((w-dw)/2), math.floor(h/3)
  368.   local dialog=main:addFrame():setPosition(dx,dy):setSize(dw,dh):setBackground(colors.cyan)
  369.   dialog:addLabel():setPosition(2,2):setSize(dw-4,1):setText("Set Basalt reinstall policy:"):setForeground(colors.white)
  370.  
  371.   local choice=nil; local btnX,btnW,btnH=2, dw-4, 2; local y=4
  372.   dialog:addButton():setPosition(btnX,y):setSize(btnW,btnH):setText("Always"):setBackground(colors.green):setForeground(colors.white)
  373.         :onClick(function() choice="always" end); y=y+btnH
  374.   dialog:addButton():setPosition(btnX,y):setSize(btnW,btnH):setText("Never"):setBackground(colors.red):setForeground(colors.white)
  375.         :onClick(function() choice="never" end); y=y+btnH
  376.   dialog:addButton():setPosition(btnX,y):setSize(btnW,btnH):setText("Ask"):setBackground(colors.gray):setForeground(colors.white)
  377.         :onClick(function() choice="ask" end)
  378.  
  379.   while not choice do sleep(0.05) end
  380.   removeElement(dialog)
  381.   CFG.reinstall_basalt = choice
  382.   CFG.hasInstalled = true
  383.   saveConfig(CFG)
  384.   addLog("Saved Basalt policy: "..choice, "SUCCESS")
  385. end
  386.  
  387. local function computeTotals()
  388.   local n=0; for path,_ in pairs(FILE_MAP) do if not isBlacklisted(path) then n=n+1 end end
  389.   state.total_files = n
  390. end
  391.  
  392. local function cleanInstall()
  393.   addLog("Starting clean installation...", "INFO")
  394.   local protected={"rom","ROM","install.lua","install_network.lua","basalt.lua","basalt","netinst.cfg"}
  395.   for _,p in ipairs(CFG.blacklist or {}) do table.insert(protected, p) end
  396.   local items = fs.list("/")
  397.   local deleted=0
  398.   for _, it in ipairs(items) do
  399.     local prot=false; for _,p in ipairs(protected) do if it==p or it:sub(1,#p+1)==p.."/" then prot=true; break end end
  400.     if not prot then fs.delete(it); deleted=deleted+1; addLog("Removed: "..it, "INFO") end
  401.   end
  402.   addLog("Clean install completed - removed "..deleted.." items", "SUCCESS")
  403. end
  404.  
  405. local function createDirectories()
  406.   addLog("Creating directory structure...", "INFO")
  407.   for _,d in ipairs(DIRECTORIES) do
  408.     if not isBlacklisted(d) and not fs.exists(d) then fs.makeDir(d) end
  409.   end
  410.   addLog("Directory structure created", "SUCCESS")
  411. end
  412.  
  413. local function httpGetWithRetries(url, retries)
  414.   local attempt=0
  415.   while attempt < (retries or 2) do
  416.     attempt = attempt + 1
  417.     local r = http.get(url)
  418.     if r then return r, attempt end
  419.     sleep(0.2)
  420.   end
  421.   return nil, attempt
  422. end
  423.  
  424. local function downloadFile(local_path, github_path)
  425.   if isBlacklisted(local_path) then
  426.     table.insert(state.skipped_blacklisted, local_path)
  427.     addLog("Skipped (blacklisted): "..local_path, "WARNING")
  428.     state.progress = state.progress + 1; updateProgress()
  429.     return true
  430.   end
  431.   state.current_file = local_path; updateProgress()
  432.  
  433.   local url = GITHUB_REPO.."/"..github_path
  434.   local resp, tries = httpGetWithRetries(url, CFG.retries or 2)
  435.   if not resp then
  436.     addLog(("Failed to download after %d attempt(s): %s"):format(tries, local_path), "ERROR")
  437.     table.insert(state.failed_files, local_path)
  438.     state.progress = state.progress + 1; updateProgress()
  439.     return false
  440.   end
  441.   local content = resp.readAll(); local code = resp.getResponseCode(); resp.close()
  442.   if code ~= 200 or not content then
  443.     addLog(("HTTP %s on %s"):format(tostring(code), local_path), "ERROR")
  444.     table.insert(state.failed_files, local_path)
  445.     state.progress = state.progress + 1; updateProgress()
  446.     return false
  447.   end
  448.   local dir = fs.getDir(local_path)
  449.   if dir ~= "" and not fs.exists(dir) and not isBlacklisted(dir) then fs.makeDir(dir) end
  450.   if local_path == "basalt.lua" and isBlacklisted("basalt.lua") then
  451.     addLog("Skipped overwrite of basalt.lua (blacklisted)", "WARNING")
  452.   else
  453.     local f = fs.open(local_path, "w")
  454.     if not f then
  455.       addLog("Cannot create file: "..local_path, "ERROR")
  456.       table.insert(state.failed_files, local_path)
  457.       state.progress = state.progress + 1; updateProgress()
  458.       return false
  459.     end
  460.     f.write(content); f.close()
  461.     addLog("Downloaded: "..local_path, "SUCCESS")
  462.   end
  463.   state.success_count = state.success_count + 1
  464.   state.progress = state.progress + 1; updateProgress()
  465.   return true
  466. end
  467.  
  468. local function installFiles()
  469.   addLog("Starting file installation...", "INFO")
  470.   computeTotals()
  471.   state.progress, state.success_count = 0, 0; updateProgress()
  472.  
  473.   for lp, gp in pairs(FILE_MAP) do
  474.     downloadFile(lp, gp)
  475.     sleep(0) -- yield to UI
  476.   end
  477.  
  478.   statusLabel:setText("Installation completed")
  479.   state.progress = state.total_files; state.current_file = ""; updateProgress(); sleep(0)
  480.  
  481.   local failed = #state.failed_files
  482.   if failed > 0 then
  483.     addLog("Installation completed with "..failed.." failure(s)", "ERROR")
  484.   else
  485.     if #state.skipped_blacklisted > 0 then
  486.       addLog("Skipped blacklisted: "..table.concat(state.skipped_blacklisted, ", "), "WARNING")
  487.     end
  488.     addLog("All files installed successfully!", "SUCCESS")
  489.   end
  490.   return failed == 0
  491. end
  492.  
  493. local function showChoiceDialog()
  494.   local w,h=termSize()
  495.   local dw=math.max(34, math.floor(w*3/4)); if dw>w-2 then dw=w-2 end
  496.   local dh=14; local dx,dy=math.floor((w-dw)/2), math.floor(h/3)
  497.   local d=main:addFrame():setPosition(dx,dy):setSize(dw,dh):setBackground(colors.orange)
  498.   d:addLabel():setPosition(2,2):setSize(dw-4,1):setText("Existing Installation Found"):setForeground(colors.white)
  499.   d:addLabel():setPosition(2,4):setSize(dw-4,1):setText("Choose installation method:"):setForeground(colors.white)
  500.  
  501.   local choice=nil; local btnX,btnW,btnH=2, dw-4, 2; local y=7
  502.   d:addButton():setPosition(btnX,y):setSize(btnW,btnH):setText("Clean Install"):setBackground(colors.red):setForeground(colors.white)
  503.     :onClick(function() choice="clean" end); y=y+btnH
  504.   d:addButton():setPosition(btnX,y):setSize(btnW,btnH):setText("Update Files"):setBackground(colors.green):setForeground(colors.white)
  505.     :onClick(function() choice="update" end); y=y+btnH
  506.   d:addButton():setPosition(btnX,y):setSize(btnW,btnH):setText("Cancel"):setBackground(colors.gray):setForeground(colors.white)
  507.     :onClick(function() choice="cancel" end)
  508.  
  509.   while not choice do sleep(0.05) end
  510.   removeElement(d)
  511.   return choice
  512. end
  513.  
  514. local function showEndDialog(success)
  515.   local w,h=termSize()
  516.   local dw=math.max(34, math.floor(w*3/4)); if dw>w-2 then dw=w-2 end
  517.   local dh=8; local dx,dy=math.floor((w-dw)/2), math.floor(h/3)
  518.   local d=main:addFrame():setPosition(dx,dy):setSize(dw,dh):setBackground(success and colors.green or colors.red)
  519.   d:addLabel():setPosition(2,2):setSize(dw-4,1):setText(success and "Installation Successful!" or "Installation Failed!"):setForeground(colors.white)
  520.   d:addLabel():setPosition(2,4):setSize(dw-4,1):setText(success and "Network system ready to use" or "Check log for error details"):setForeground(colors.white)
  521.   local done=false
  522.   d:addButton():setPosition(math.floor(dw/2)-4,6):setSize(8,1):setText("OK")
  523.     :setBackground(colors.white):setForeground(colors.black):onClick(function() done=true end)
  524.   while not done do sleep(0.05) end
  525.   removeElement(d)
  526. end
  527.  
  528. local function runInstaller()
  529.   -- init UI + logs
  530.   createGUI(); logInit()
  531.   addLog("Network installer started","INFO")
  532.   addLog("Computer ID: "..os.getComputerID(),"INFO")
  533.  
  534.   -- optional cooperative cleanup (usually quiet after reboot already)
  535.   if CFG.kill_processes then
  536.     addLog("Process cleanup enabled (cooperative)","INFO")
  537.   end
  538.  
  539.   -- first GUI run: persist Basalt policy
  540.   if CFG.hasInstalled ~= true then firstRunPolicyDialog() end
  541.  
  542.   local has_existing = fs.exists("bin") or fs.exists("lib") or fs.exists("protocols") or fs.exists("startup.lua")
  543.   local mode = CFG.install_mode or "ask"
  544.   if mode == "ask" and has_existing then
  545.     mode = showChoiceDialog()
  546.     if mode == "cancel" then addLog("Installation cancelled by user","WARNING"); logClose(); _G.__INSTALLER_RUNNING=false; return end
  547.   end
  548.  
  549.   if mode == "clean" then cleanInstall() end
  550.   createDirectories()
  551.  
  552.   local ok = installFiles()
  553.   showEndDialog(ok)
  554.   logClose()
  555.   _G.__INSTALLER_RUNNING=false
  556. end
  557.  
  558. local function uiLoop()
  559.   _G.__INSTALLER_RUNNING=true
  560.   while _G.__INSTALLER_RUNNING do
  561.     local ev={os.pullEventRaw()}
  562.     basalt.update(table.unpack(ev))
  563.   end
  564. end
  565.  
  566. parallel.waitForAny(uiLoop, runInstaller)
  567.  
  568. -- Back to a clean terminal and hand off to startup.lua
  569. term.clear(); term.setCursorPos(1,1)
  570. if fs.exists("startup.lua") then shell.run("startup.lua") end
  571. ]=]
  572.  
  573.   local f = fs.open("install_network.lua", "w")
  574.   if not f then error("Cannot create install_network.lua") end
  575.   f.write(code)
  576.   f.close()
  577. end
  578.  
  579. -- ===== main (reboot gate then GUI) =====
  580. term.clear(); term.setCursorPos(1,1)
  581. printColored("CC Network System Installer - Stage 1", colors.cyan)
  582. printColored("=====================================", colors.cyan)
  583. print()
  584.  
  585. local CFG = loadConfig()
  586.  
  587. -- Reboot gate using start_background_processes
  588. if CFG.start_background_processes ~= false then
  589.   -- First invocation: turn off background processes and reboot.
  590.   CFG.start_background_processes = false
  591.   saveConfig(CFG)
  592.   print("Preparing system for installation...")
  593.   print("Disabling background processes and rebooting safely.")
  594.   sleep(1)
  595.   os.reboot()
  596.   return
  597. else
  598.   -- Post-reboot: turn flag back on for future normal boots
  599.   CFG.start_background_processes = true
  600.   saveConfig(CFG)
  601. end
  602.  
  603. -- HTTP API available?
  604. if not http then
  605.   printColored("\nERROR: HTTP API not available", colors.red)
  606.   printColored("Enable HTTP API in ComputerCraft config", colors.red)
  607.   return
  608. end
  609.  
  610. -- Quick connectivity test
  611. print("\nTesting internet connection...")
  612. if not checkInternet(3) then
  613.   printColored("ERROR: No internet connection", colors.red)
  614.   printColored("Please check your connection and try again", colors.yellow)
  615.   return
  616. end
  617. printColored("Internet: OK", colors.green)
  618. print()
  619.  
  620. -- Basalt dependency
  621. print("Handling Basalt installation...")
  622. if not handleBasaltPolicy(CFG) then
  623.   printColored("\nERROR: Basalt is required for the GUI installer", colors.red)
  624.   printColored("Please fix the issue and try again", colors.yellow)
  625.   return
  626. end
  627.  
  628. -- Generate GUI installer and run it
  629. local okWrite, errWrite = pcall(writeGUIInstaller)
  630. if not okWrite then
  631.   printColored("\nERROR: Failed to write installer", colors.red)
  632.   printColored("Error: "..tostring(errWrite), colors.red)
  633.   return
  634. end
  635.  
  636. printColored("\nNetwork installer created successfully", colors.green)
  637. print("Starting GUI installer in 2 seconds...")
  638. sleep(2)
  639.  
  640. local okRun, errRun = pcall(function() shell.run("install_network.lua") end)
  641. if not okRun then
  642.   printColored("\nERROR: GUI installer failed to run", colors.red)
  643.   printColored("Error: "..tostring(errRun), colors.red)
  644. end
  645.  
  646. print("\nInstaller completed.")
  647.  
Advertisement
Comments
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
Add Comment
Please, Sign In to add comment