-- Salt's ComputerCraft Storage Network Script
--
-- For information on this script, physical in-world setup, and configuration,
-- see: https://git.desu.ltd/salt/mc-scripts/src/branch/master/storage-net

-- Default configuration values. Override in config.lua. DO NOT CHANGE HERE
mode                = "ConfigureMe"     -- The mode of function for this node
networkid           = 0                 -- Unique ID for this network
port_broadcast      = 42914             -- Port for M->S traffic
port_return         = 42915             -- Port for S->M traffic

-- This loads config.lua. See masterconfig.lua and slaveconfig.lua for example
-- configurations.
require "config"

-- Startup diagnostics
print("Salt's CC Storage Net")
print("Computer ID: " .. os.getComputerID())
print("Computer " .. os.getComputerID() .. " running as " .. mode)

-- Common globals
modem = peripheral.find("modem") or error("No modem attached", 0)
-- Master globals
-- Slave globals

-- Common functions
function c_mainLoop(loopfunc)
    -- Loops a thing forever
    while true do
        loopfunc()
        sleep(0.10)
    end
end
-- Master functions
function m_loop()
    -- The main loop of the master server
    -- Listen for packets on the return net. This has a timeout for events and stuff
    local timeout = os.startTimer(1)
    local event, side, channel, replyChannel, message, distance = os.pullEvent()
    if (event == "modem_message") then
        print("Message received: " .. message)
    end
    sleep(1)
end
-- Slave functions
function s_loop()
    -- The main loop of any slave nodes
    -- Listen for packets from the master
    local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
    sleep(1)
end

-- Application entrypoint
function main ()
    if (mode == "master") then
        modem.open(port_return)
        c_mainLoop(m_loop)
    elseif (mode == "slave") then
        modem.open(port_broadcast)
        c_mainLoop(s_loop)
    else
        error("Invalid mode: " .. mode .. ", please configure this node appropriately", 0)
    end
    modem.closeAll()
end

main()