--[[

░██████╗███████╗███╗░░██╗████████╗██╗███╗░░██╗███████╗██╗░░░░░
██╔════╝██╔════╝████╗░██║╚══██╔══╝██║████╗░██║██╔════╝██║░░░░░
╚█████╗░█████╗░░██╔██╗██║░░░██║░░░██║██╔██╗██║█████╗░░██║░░░░░
░╚═══██╗██╔══╝░░██║╚████║░░░██║░░░██║██║╚████║██╔══╝░░██║░░░░░
██████╔╝███████╗██║░╚███║░░░██║░░░██║██║░╚███║███████╗███████╗
╚═════╝░╚══════╝╚═╝░░╚══╝░░░╚═╝░░░╚═╝╚═╝░░╚══╝╚══════╝╚══════╝

████████╗██╗░░██╗███████╗  ██████╗░███████╗░██████╗████████╗
╚══██╔══╝██║░░██║██╔════╝  ██╔══██╗██╔════╝██╔════╝╚══██╔══╝
░░░██║░░░███████║█████╗░░  ██████╦╝█████╗░░╚█████╗░░░░██║░░░
░░░██║░░░██╔══██║██╔══╝░░  ██╔══██╗██╔══╝░░░╚═══██╗░░░██║░░░
░░░██║░░░██║░░██║███████╗  ██████╦╝███████╗██████╔╝░░░██║░░░
░░░╚═╝░░░╚═╝░░╚═╝╚══════╝  ╚═════╝░╚══════╝╚═════╝░░░░╚═╝░░░

░█████╗░███╗░░██╗████████╗██╗░░░░░░░█████╗░██████╗░░█████╗░░██████╗██╗░░██╗
██╔══██╗████╗░██║╚══██╔══╝██║░░░░░░██╔══██╗██╔══██╗██╔══██╗██╔════╝██║░░██║
███████║██╔██╗██║░░░██║░░░██║█████╗██║░░╚═╝██████╔╝███████║╚█████╗░███████║
██╔══██║██║╚████║░░░██║░░░██║╚════╝██║░░██╗██╔══██╗██╔══██║░╚═══██╗██╔══██║
██║░░██║██║░╚███║░░░██║░░░██║░░░░░░╚█████╔╝██║░░██║██║░░██║██████╔╝██║░░██║
╚═╝░░╚═╝╚═╝░░╚══╝░░░╚═╝░░░╚═╝░░░░░░░╚════╝░╚═╝░░╚═╝╚═╝░░╚═╝╚═════╝░╚═╝░░╚═╝

█▀█ █▀█ █▀█ █░█ █ █▀▄ █▀▀ █▀▄   █▄▄ █▄█   █░░ █ █▄▄ █▄▄ █▄█ ▀ █▀   █▀ ▄▀█ █▄░█ █▀▄ █▄▄ █▀█ ▀▄▀
█▀▀ █▀▄ █▄█ ▀▄▀ █ █▄▀ ██▄ █▄▀   █▄█ ░█░   █▄▄ █ █▄█ █▄█ ░█░ ░ ▄█   ▄█ █▀█ █░▀█ █▄▀ █▄█ █▄█ █░█

█▀▄▀█ ▄▀█ █▀█ █▀▀ █░█   █▄▄   ▀█ █▀█ ▀█ ▀█   █▀ █▀▀ █▀█ ▄▀█ █▀█ █▀█ █▀▀ █▀▄   █░█ █▀▀ █▀█ █▀ █ █▀█ █▄░█
█░▀░█ █▀█ █▀▄ █▄▄ █▀█   █▄█   █▄ █▄█ █▄ █▄   ▄█ █▄▄ █▀▄ █▀█ █▀▀ █▀▀ ██▄ █▄▀   ▀▄▀ ██▄ █▀▄ ▄█ █ █▄█ █░▀█

]]--

--[[
this is sentinel, an anti-crash lag prevention system for Libby's Sandbox
also used on rose's server

entity ghosting, lag prevention when major lag detected, and crash prevention for tools
[NOT A PROP PROTECTION SYSTEM]
]]--


propdisabled = 0

local function spawnDisable(ply)
    if propdisabled == 1 then
        ply:SendLua("chat.AddText('[Sentinel] Ent cannot spawn. Sentinel is trying to prevent lag activity')")

        return false
    end
end

hook.Add("PlayerSpawnProp", "sentinel_propspawndisabled", spawnDisable)
hook.Add("PlayerSpawnSENT", "sentinel_propspawndisabled", spawnDisable)
hook.Add("PlayerSpawnVehicle", "sentinel_propspawndisabled", spawnDisable)
-- 5/6/2021
-- fuck.... time to modify this again!
-- Weekly backups ain't weekly backups no more!
-- At least they should remember backing up the lua files this time
-- needed
libby_lagdet_counter = 0
lag_counter = 0
libby_cleanup_server_counter = 0
libby_constant_lag_server_counter = 0
libby_date = os.date()
suspicioususer = 0
disablephysics = 0
cleanupcount = 0

-- needed
if SERVER then
    local lagrange = CreateConVar("lagdet_range", "0.02", {FCVAR_SERVER_CAN_EXECUTE})

    local lagcount = CreateConVar("lagdet_count", "10", {FCVAR_SERVER_CAN_EXECUTE})

    local lagquiet = CreateConVar("lagdet_quiet", "10", {FCVAR_SERVER_CAN_EXECUTE})

    local lagverbose = CreateConVar("lagdet_verbose", "0", {FCVAR_SERVER_CAN_EXECUTE})

    local lagexecute = CreateConVar("lagdet_execute", "gay", {FCVAR_SERVER_CAN_EXECUTE})

    --local lagexecute = CreateConVar( "lagdet_execute", "ulx consay [LAGDETECTOR] Server is currently detecting measureable lag.", { FCVAR_SERVER_CAN_EXECUTE } )
    local lagcount_meltdown = CreateConVar("lagcount_meltdown", "100", {FCVAR_SERVER_CAN_EXECUTE})

    local lagexecute_meltdown = CreateConVar("lagexecute_meltdown", "dgddhfdhfjgj", {FCVAR_SERVER_CAN_EXECUTE})

    --local lagexecute_meltdown = CreateConVar( "lagexecute_meltdown", "ulx maprestart", { FCVAR_SERVER_CAN_EXECUTE } )
    -----------------------------------------------------------------------------------------------
    -----------------------------------------------------------------------------------------------
    local lastSysCurrDiff = 9999
    local deltaSysCurrDiff = 0
    local currcount = 0
    local clearTime = 0
    local framecount = 0

    concommand.Add("lagdet_clearcount", function()
        currcount = 0
    end)

    hook.Add("Think", "LagDetThink", function()
        framecount = framecount + 1
    end)

    -- Calculate lag by comparing SysTime to CurTime.  
    -- Increased differential indicates potential lag
    local function GetCurrentDelta()
        --local frametime = FrameTime()
        --fps = 1 / frametime
        local SysCurrDiff = SysTime() - CurTime() -- current differential
        deltaSysCurrDiff = math.Round(SysCurrDiff - lastSysCurrDiff, 6) -- change in differential since last check
        lastSysCurrDiff = SysCurrDiff

        return deltaSysCurrDiff
    end

    local function urlencode(str)
        if str then
            str = string.gsub(str, "\n", "\r\n")
            str = string.gsub(str, "([^%w ])", function(c) return string.format("%%%02X", string.byte(c)) end)
            str = string.gsub(str, " ", "+")
        end

        return str
    end

    -- I am super angry!!!!
    -- Lmao just kidding
    -- something
    -- 66 tick only
    RunConsoleCommand("lagdet_range", "0.025")
    -- 33 tick only
    --RunConsoleCommand("lagdet_range", "0.017")

    function libre_checkents(ent)
        local ent = ents.FindByClass("prop_physics")

        for _, ent in pairs(ent) do
            local pos = ent:GetPos()
            local propsnear = ents.FindInSphere(pos, 0.25)
            local stackent = 0

            for k, v in pairs(propsnear) do
                local whatisthatent = ent:GetClass()
                local whatisthatmodel = ent:GetModel()

                if whatisthatent == "prop_physics" then
                    stackent = stackent + 1

                    if stackent > 18 then
                        PrintMessage(HUD_PRINTCONSOLE, "[Sentinel]: " .. ent:GetModel() .. " removed :) (sentinel lag detection)")
                        ent:Remove()
                        stackent = 0
                        --timer.Create("libre_warnsuspiciousentities", 0.6, 1, function() PrintMessage(HUD_PRINTTALK, "[libre]: entity: " .. whatisthatent .. " model: " .. whatisthatmodel .. "") end)
                    end

                    -- if lolno > 999999999999999999999999999999999999999999999999999999999999999 then
                    --     -- We set all props collision to not collide with each other. duh
                    --     lolno = 0
                    --     net.Start("sentinel_notif")
                    --     net.WriteString("[libby_lag_prevention]: Thanks, (anti_stacker_preventions_executed)")
                    --     net.WriteInt("NOTIFY_GENERIC")
                    --     net.WriteInt(6)
                    --     net.Broadcast()

                    --     timer.Create("libre_bruhhetryingtocrashserver", 0, 1000, function()
                    --         local Ent = ents.FindByClass("prop_physics")

                    --         for _, Ent in pairs(Ent) do
                    --             if Ent:IsValid() then
                    --                 Ent:SetCollisionGroup(COLLISION_GROUP_WORLD)
                    --             end
                    --         end
                    --     end)
                    -- end
                end
            end
        end
    end

function libre_haltexplosions()
PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] Halted explosions (method 1)") 
//env_explosion
local ent = ents.FindByClass("env_explosion")
for _,ent in pairs(ent) do
if ent:IsValid() then
ent:Remove()
end
end
end

function libre_haltexplosions2()
PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] Halted explosions (method 1)") 
//env_explosion
local ent = ents.FindByClass("entityflame")
for _,ent in pairs(ent) do
if ent:IsValid() then
ent:Remove()
end
end
end

function libre_haltexplosions3()
PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] Halted explosions (method 2)") 
//env_explosion
local ent = ents.FindByClass("prop_physics")
for _,ent in pairs(ent) do
if ent:IsValid() then
if ent:GetModel() == "models/props_c17/oildrum001_explosive.mdl" then
ent:Remove()
end
end
end
end

function libre_haltexplosions4()
PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] Halted explosions (method 2)") 
//env_explosion
local ent = ents.FindByClass("prop_physics")
for _,ent in pairs(ent) do
if ent:IsValid() then
if ent:GetModel() == "models/props_phx/amraam.mdl" or ent:GetModel() == "models/props_phx/mk-82.mdl" then
ent:Remove()
end
end
end
end

    --
    -- Brought to you by Lenn
    -- In an event of a lag has ben detected, Something is up
    -- We better do something before shit goes worst by now 1/8/2022
    -- preventing server crashing faggots ever since 
    -- This code makes sure nobody is allowed to spawn props when the lag prevention commands the server to disallow prop spawning.
    timer.Create("sentinel_nophysicscheck", 0, 0, function()
        if nophysics == "1" then
        end
    end)

    timer.Create("libby_triggerlagprevention", 0.01, 0, function()
        if libby_lagdet_counter > 6 then
            PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] (stage 1) lag prevention payload, start!")

            function libre_freezeall()
                local ent = ents.FindByClass("*")

                for _, ent in pairs(ent) do
                    if ent:IsValid() then
                        --entityfound = entityfound + 1
                        local phys = ent:GetPhysicsObject()

                        if IsValid(phys) then
                            ----print("[Sentinel]: Yo this entity has physics!")
                            if not ent:IsPlayer() then
                                phys:EnableMotion(false)
                            end

                            if not ent:IsPlayer() then
                                ent:SetCollisionGroup(COLLISION_GROUP_INTERACTIVE)
                            end
                        end
                    end
                end
            end

            libre_checkents()
            libre_freezeall()
            -- As fast as we can, must freeze every possible entity on the server and check entities
            -- Allow spawning props to be disabled, to prevent further damage to our server network!
            propdisabled = 1
            propdisabled = 1
            propdisabled = 1
            propdisabled = 1

            timer.Create("sentinel_allowpropspawningman", 3, 1, function()
                propdisabled = 0
            end)

            -- It's also the time to start disabling physics for a short time to prevent even more further damage to our server network
            nophysics = 1
            nophysics = 1
            disablephysics = 1
            disablephysics = 1

            timer.Create("sentinel_nophysics_start", 1, 5, function()
                nophysics = 1
                nophysics = 1
                disablephysics = 1
                disablephysics = 1
            end)

            timer.Create("sentinel_turnbackphysicsonrightnow", 5.25, 1, function()
                nophysics = 0
                disablephysics = 0
            end)

            -- No duplicators allowed at this time, There is some serious lag going on!
            denieddupe = 1

            timer.Create("denieddupe_reset", 6, 1, function()
                denieddupe = 0
            end)

            -- We would also like to disable collisions on every single prop to further minimize the risk of potential server crashing by collision
            local ent = ents.FindByClass("prop_physics")

            for _, ent in pairs(ent) do
                if ent:IsValid() then
                    ent:SetCollisionGroup(COLLISION_GROUP_INTERACTIVE_DEBRIS)
                end
            end

            PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] (stage 2) attempted to prevent further server lag")
            sleepphysics = 0
            physicsprop = 0
            frozenphysics = 0

            -- Notify peasants lag prevention payload has executed
            --sentinel.Broadcast("⚠ medium lag detected, payload executed ⚠ (lag percentage: " .. sentinellagpercent .. "%)")
            if sentinellagpercent > 1 and sentinellagpercent < 5 then
                sentinel.Broadcast("⚠ medium lag detected, payload executed ⚠ intensity (|) " .. sentinellagpercent .. "%")
            elseif sentinellagpercent > 5 and sentinellagpercent < 10 then
                sentinel.Broadcast("⚠ medium lag detected, payload executed ⚠ intensity (||) " .. sentinellagpercent .. "%")
            elseif sentinellagpercent > 10 and sentinellagpercent < 15 then
                sentinel.Broadcast("⚠ medium lag detected, payload executed ⚠ intensity (|||) " .. sentinellagpercent .. "%")
            else
                sentinel.Broadcast("⚠ medium lag detected, payload executed ⚠ intensity (???) " .. sentinellagpercent .. "%")
            end

            cleanupcount = cleanupcount + 1

            timer.Create("sentinel_resetcleanupcount", 5, 1, function()
                cleanupcount = 0
            end)

            -- Notify peasants lag prevention payload has executed (along with an auto-cleanup system)
            if cleanupcount > 10 then
                RunConsoleCommand("gmod_admin_cleanup")
                sentinel.Broadcast("⚠ Excessive lag, Cleaning up map! ⚠")
            end

            PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] (stage 3) lag prevention notifications")

            -- Freeze and check everything before allowing physics again :)
            timer.Create("sentinel_checkbeforeallowphysics", 7, 1, function()
                PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] stage (4) freezing and checking entities before allowing physics")
                libre_checkents()
                libre_freezeall()
            end)

            -- freeze people who used duplicator in the past :/
            if not duplicatorusernick == 0 then
                local ply = player.GetBySteamID(duplicatorusernick)
                if not IsValid(ply) then return end

                if sentinel.PermissionCheck(ply) then
                    sentinel.Broadcast(ply:Nick() .. " was spared from being frozen due to having the permission :(")

                    return
                end


// fucking aids
if not duplicatorusernick == 0 then
sentinel.Broadcast("Blocked " .. ply:Nick() .. " from using the duplicator tool!")
return false
end

                sentinel.Broadcast(ply:Nick() .. "(" .. duplicatorusernick .. ")" .. " got frozen for using the duplicator tool")
                ply:Lock()
                net.Start("sentinel_notif")
                net.WriteString("Sentinel froze you to make sure you aren't causing lag!")
                net.WriteInt(NOTIFY_ERROR, 5)
                net.WriteInt(6, 5)
                net.Send(ply)
                net.Start("sentinel_frozen")
                net.Send(ply)

                -- Unfreeze them
                timer.Create("sentinel_unfreezebroo", 5, 1, function()
                    if not IsValid(ply) then return end
                    sentinel.Broadcast(ply:Nick() .. "(" .. duplicatorusernick .. ")" .. " was unfrozen")
                    ply:UnLock()
                end)


            end

                -- wow, even too many explosions can cause lag! delete all env_explosion
                libre_haltexplosions()
                libre_haltexplosions2()
                libre_haltexplosions3()
                libre_haltexplosions4()
            --
            lag_counter = lag_counter + 3
            libby_lagdet_counter = 0

            timer.Create("nolagfunctionstartfornow", 0.05, 20, function()
                libby_lagdet_counter = 0
            end)
        end
    end)

    timer.Create("libby_no_negative_countah", 0, 0, function()
        if libby_lagdet_counter < 0 then
            libby_lagdet_counter = 0
        end
    end)

    timer.Create("libby_cleanupmap_when", 0.25, 0, function()
        if libby_cleanup_server_counter > 80 then
            --print("[Sentinel]: 80 expected lag counts per second! What the fuck! Cleaning up the server.")
            sentinel.Broadcast("Server has been cleaned up due to constant lag.")
            RunConsoleCommand("gmod_admin_cleanup")
            --libby_date = os.date()
            --data = file.Read("libbylagpreventionlog.txt") if ( data ) then file.Append( "libbylagpreventionlog.txt", "\r\n [libby_lag_prevention_log]: [BAD ALERT]: Servers been lagging with no unresolvable method to stop. Cleaning up map.       Time: " .. libby_date .. "" ) end
            libby_cleanup_server_counter = 0
        end
    end)

    timer.Create("libby_lagprevention_doyourjob", 0.25, 0, function()
        if libby_constant_lag_server_counter > 24 then
            --print("[Sentinel]: 20 expected minimal lag counts in minutes! What the fuck! Executing lag prevention.")
            PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] (stage 1) lag prevention payload, start!")

            function libre_freezeall()
                local ent = ents.FindByClass("*")

                for _, ent in pairs(ent) do
                    if ent:IsValid() then
                        --entityfound = entityfound + 1
                        local phys = ent:GetPhysicsObject()

                        if IsValid(phys) then
                            ----print("[Sentinel]: Yo this entity has physics!")
                            if not ent:IsPlayer() then
                                phys:EnableMotion(false)
                            end

                            if not ent:IsPlayer() then
                                ent:SetCollisionGroup(COLLISION_GROUP_INTERACTIVE)
                            end
                        end
                    end
                end
            end

            libre_checkents()
            libre_freezeall()
            -- As fast as we can, must freeze every possible entity on the server and check entities
            -- Allow spawning props to be disabled, to prevent further damage to our server network!
            propdisabled = 1

            timer.Create("sentinel_allowpropspawningman", 3, 1, function()
                propdisabled = 0
            end)

            -- It's also the time to start disabling physics for a short time to prevent even more further damage to our server network
            nophysics = 1
            disablephysics = 1

            timer.Create("sentinel_nophysics_start", 1, 4, function()
                nophysics = 1
                disablephysics = 1
            end)

            timer.Create("sentinel_turnbackphysicsonrightnow", 5, 1, function()
                nophysics = 0
                disablephysics = 0
            end)

            -- No duplicators allowed at this time, There is some serious lag going on!
            denieddupe = 1

            timer.Create("denieddupe_reset", 6, 1, function()
                denieddupe = 0
            end)

            -- We would also like to disable collisions on every single prop to further minimize the risk of potential server crashing by collision
            local ent = ents.FindByClass("prop_physics")

            for _, ent in pairs(ent) do
                if ent:IsValid() then
                    ent:SetCollisionGroup(COLLISION_GROUP_INTERACTIVE_DEBRIS)
                end
            end

            PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] (stage 2) attempted to prevent further server lag")
            sleepphysics = 0
            physicsprop = 0
            frozenphysics = 0
            sentinel.Broadcast("⚠ Consistent lag detected, payload executed ⚠")
            cleanupcount = cleanupcount + 1

            timer.Create("sentinel_resetcleanupcount", 5, 1, function()
                cleanupcount = 0
            end)

            -- Notify peasants lag prevention payload has executed (along with an auto-cleanup system)
            if cleanupcount > 10 then
                RunConsoleCommand("gmod_admin_cleanup")
                sentinel.Broadcast("⚠ Excessive lag, Cleaning up map! ⚠")
            end

            PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] (stage 3) lag prevention notifications")

            -- Freeze and check everything before allowing physics again :)
            timer.Create("sentinel_checkbeforeallowphysics", 7, 1, function()
                PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] stage (4) freezing and checking entities before allowing physics")
                libre_checkents()
                libre_freezeall()
            end)

            -- freeze people who used duplicator in the past :/
            if not duplicatorusernick == 0 then
                ply = player.GetBySteamID(duplicatorusernick)

                if IsValid(ply) then
                    if sentinel.PermissionCheck(ply) then
                        sentinel.Broadcast(ply:Nick() .. " was spared from being frozen due to having the permission :(")

                        return
                    end


// fucking aids
if not duplicatorusernick == 0 then
sentinel.Broadcast("Blocked " .. ply:Nick() .. " from using the duplicator tool!")
return false
end

                sentinel.Broadcast(ply:Nick() .. "(" .. duplicatorusernick .. ")" .. " got frozen for using the duplicator tool")
                ply:Lock()
                net.Start("sentinel_notif")
                net.WriteString("Sentinel froze you to make sure you aren't causing lag!")
                net.WriteInt(NOTIFY_ERROR, 5)
                net.WriteInt(6, 5)
                net.Send(ply)
                net.Start("sentinel_frozen")
                net.Send(ply)

                -- Unfreeze them
                timer.Create("sentinel_unfreezebroo", 5, 1, function()
                    if not IsValid(ply) then return end
                    sentinel.Broadcast(ply:Nick() .. "(" .. duplicatorusernick .. ")" .. " was unfrozen")
                    ply:UnLock()
                end)


                    sentinel.Broadcast(ply:Nick() .. "(" .. duplicatorusernick .. ")" .. " got frozen for using the duplicator tool")
                    ply:Lock()
                    net.Start("sentinel_notif")
                    net.WriteString("Sentinel froze you to make sure you aren't causing lag!")
                    net.WriteInt(NOTIFY_ERROR, 5)
                    net.WriteInt(6, 5)
                    net.Send(ply)
                    net.Start("sentinel_frozen")
                    net.Send(ply)

                end

                -- Unfreeze them
                timer.Create("sentinel_unfreezebroo", 5, 1, function()
                    for k, v in pairs(player.GetAll()) do
                        v:UnLock()
                    end

                    sentinel.Broadcast("Unfroze all players")
                end)
            end

            --[[
        -- wow, even too many explosions can cause lag! delete all env_explosion
        libre_haltexplosions()
        libre_haltexplosions2()
        libre_haltexplosions3()
        libre_haltexplosions4()
        ]]
            --
            lag_counter = lag_counter + 3
            --libby_date = os.date()
            --data = file.Read("libbylagpreventionlog.txt") if ( data ) then file.Append( "libbylagpreventionlog.txt", "\r\n [libby_lag_prevention_log]: [BAD ALERT]: 20 minimal lag counts detected in minutes, Perhaps something is bad? START LAG PREVENTION       Time: " .. libby_date .. "" ) end
            libby_constant_lag_server_counter = 0
        end
    end)

    libre_lagss = 0
    lagscounter = 0
    fuck11 = 0
    moments354 = 0

    local function LagMonThreshold()
        -- i haz lag?
        if currcount > 0 then
            -- passed our clear time?
            if RealTime() > clearTime then
                currcount = 0 -- clear!                        
                --ServerLog("[LAGDETECTOR] Lag has subsided\n")
                local returnedValue = hook.Run("LagDetectorQuiet")
            end
        end

        local delt = GetCurrentDelta()

        if lagverbose:GetInt() == 1 or delt >= lagrange:GetFloat() then
            -- Oh no the lagdetector detected lag so we use it for lag prevention!
            libby_cleanup_server_counter = libby_cleanup_server_counter + 1
            libby_constant_lag_server_counter = libby_constant_lag_server_counter + 1

            timer.Simple(20, function()
                libby_cleanup_server_counter = 0
            end)

            timer.Simple(30, function()
                libby_constant_lag_server_counter = 0
            end)

            --RunConsoleCommand("libby_lag_setvelocityprop")
            libby_lagdet_counter = libby_lagdet_counter + 1
            lagscounter = lagscounter + 1

            timer.Create("didlagstop", 0.25, 1, function()
                libby_lagdet_counter = 0
                lagscounter = 0
            end)

            --if lagscounter > 0.1 and lagscounter < 3 then
            ----print("[Sentinel]: very, very minimal parts of lag detected, counter: " .. lagscounter .. "")
            --end
            -- if exceeds 4, its critical
            if lagscounter > 3.9 then
    

                timer.Create("unfreezetime", 0.5, 1, function()
                end)

                if lagscounter > 3.1 and lagscounter < 4.1 then
                    timer.Create("Sentinel_aodfkiutneraction", 1, 1, function()
                        suspicioususer = 0
                    end)
                end
            end

            if lagscounter > 8.1 then
                --if suspicioususer == 0 then print("[Sentinel]: No user with a physgun has interacted with something before lag existed") end
            end

            if lagscounter > 2.1 and lagscounter < 3.1 then
                -- Slow down time. increases server performance because physics lol
                --RunConsoleCommand("ulx","psay","quper","[Sentinel_Debug]: phys_timescale set to 0.25 (minimal lag)")

                timer.Create("unfreezetime", 1, 1, function()
                end)
            end

            --[[
                if lagscounter > 3.1 and lagscounter < 4.1 then
                local ent = ents.FindByClass("prop_physics")
                                for _,ent in pairs(ent) do
                                        if ent:IsValid() then
                                                local phys = ent:GetPhysicsObject()
                                                phys:Sleep()
                end
                end
                end
                ]]
            --
            if lagscounter > 3.1 then
                timer.Create("test", 0.1, 30, function()
                    fuck11 = fuck11 + 0.1
                end)

                timer.Create("yeahsss", 3.1, 1, function()
                    fuck11 = 0
                end)
            end

            if currcount == lagcount_meltdown:GetInt() then
                --libby_date = os.date()
                --data = file.Read("libbylagpreventionlog.txt") if ( data ) then file.Append( "libbylagpreventionlog.txt", "\r\n [libby_lag_prevention_log]: Servers been lagging with no unresolvable method to stop. Cleaning up map.       Time: " .. libby_date .. "" ) end
                game.ConsoleCommand(lagexecute_meltdown:GetString() .. "\n")
                local returnedValue = hook.Run("LagDetectorMeltdown")
            end
        end

        if delt < lagrange:GetFloat() then return false end
        currcount = currcount + 1 -- server is lagging
        --libre_lagss = libre_lagss + 1
        ----print("[libre]: lag! count: " .. libre_lagss .. " out of 20 (over 20 means significant lag)")
        clearTime = RealTime() + lagquiet:GetInt() -- bump our clear time
        if currcount == lagcount:GetInt() then return true end -- we've hit our alert threshold. 

        return false
    end

    -- really shouldn't change the periodicity!
    timer.Create("LagDetCheckPerf", 0.05, 0, function()
        if LagMonThreshold() then
            --ServerLog("[LAGDETECTOR] Lag detected!\n")
            if lagexecute:GetString() ~= "" then
                ----print("[Sentinel]: Oh no the server appears to be having a stroke activate the lag prevention!")
                --Yes this triggers the lag prevention trust me
                --lag_counter = lag_counter + 2 
                game.ConsoleCommand(lagexecute:GetString() .. "\n")
                local returnedValue = hook.Run("LagDetectorDetected")
            end
        end

        framecount = 0
    end)
end

sentinel.Broadcast("lagdetect_module loaded")