local hostname = "turtle" .. os.getComputerID()

local sides = peripheral.getNames()
for i = 1, #sides do
    if peripheral.getType(sides[i]) == "modem" then
        modemSide = sides[i]
        break
    end
end

rednet.open(modemSide)

function dump(o)
    if o == nil then
        return ""
    end

    if type(o) == 'table' then
        local s = '{ '
        for k,v in pairs(o) do
            if type(k) ~= 'number' then k = '"'..k..'"' end
            s = s .. '['..k..'] = ' .. dump(v) .. ','
        end
        return s .. '} '
    end

    return tostring(o)
end

rednet.host("rmm", hostname)
local master = rednet.lookup("rmm", "master")
while true do
    local event, id, data = os.pullEvent()
    if event == "rednet_message" then
        print(id .. " (" .. event .. ")> " .. dump(data))
        if type(data) == 'table' then
            if data[1] == 'eval' then
                local cmd_fn, err = loadstring(data[2])
                if not cmd_fn then
                    print("Compile error: " .. err)
                    rednet.send(master, "Compile error: " .. err)
                else
                    local success, output = pcall(cmd_fn)
                    if success then
                        if output then
                            print("Command output: " .. dump(output))
                            rednet.send(master, "Command output: " .. dump(output))
                        else
                            print("There is no command output.")
                            rednet.send(master, "There is no command output.")
                        end
                    else
                        print("Runtime error: " .. output)
                        rednet.send(master, "Runtime error: " .. output)
                    end
                end
            end
        elseif type(data) == 'string' then
            if data == 'ping' then
                rednet.send(master, "Pong!")
            end
        end
    end
end

rednet.close(modemSide)