local function truncate(num)
    return math.floor(num * 10000) / 10000
end

local function get_time()
    local now = os.date("*t")
    local time = now.hour * 3600 + now.min * 60 + now.sec
    return time / (24 * 3600)
end

local function sync_time()
    minetest.set_timeofday(get_time())
end

local sync_active = minetest.settings:get("real_world_time.sync_active") or "true"

local function sync_time_loop()
    if sync_active == "true" then
        local game_time = truncate(minetest.get_timeofday())
        local world_time = truncate(get_time())
        if game_time ~= world_time then
            sync_time()
        end 
    end
    minetest.after(60, sync_time_loop)
end

minetest.after(0, function()
    if sync_active == "true" then
      minetest.setting_set("time_speed", 1)
      sync_time()
    end
    sync_time_loop()
end)

minetest.register_chatcommand("sync_time", {
    privs = { server = true },
    func = function(name, _)
        minetest.setting_set("time_speed", 1)
        sync_time()
        sync_active = "true"
        minetest.settings:set("real_world_time.sync_active", sync_active)
        minetest.chat_send_player(name, "Time synced with real-world time")
    end
})

minetest.register_chatcommand("unsync_time", {
    privs = { server = true },
    func = function(name, _)
        minetest.setting_set("time_speed", 72)
        sync_active = "false"
        minetest.settings:set("real_world_time.sync_active", sync_active)
        minetest.chat_send_player(name, "Time speed has been restored to default")
    end
})

