--[[

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

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

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

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

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

]]--

--[[
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]
]]--

-- lolno = 10 //no idea what this var should be, shity code is unreadable

spawnedentityuser = 0
spawnedpropspersecond = 0
entclassswep = 0
requirevehicleclass = 0
abnormallagactivity2 = 0
disablephysics = 0
potentialservercrasher = 0
sentinel = {}


lag_counter = 0
tiny_lag_counter = 0
time_since_lag = 0
lag_detected_times = 0
lag_detects_per_minute = 0
lag_freeze_counter = 0
warn_everyone_there_is_antilag = 0
lastspawnednick = 0
lastspawnedprop = 0
denieddupe = 0
mingeblacklistednick = 0
localdumbass = 0
interactionuser = 0
localretard = 0
localfaggot = 0
vehiclecounts = 0
propcounts = 0
swepcounts = 0
sentcounts = 0
ragdollcounts = 0
npccounts = 0
suspiciousactivitycounts = 0
kickthismotherfucker = 0
thisfuckingretard = 0
physgunuser = 0
duplicatorusernick = 0
retardalert = 0
retardalert = 0
util.AddNetworkString("sentinelBroadcast")
util.AddNetworkString("sentinel_frozen")
util.AddNetworkString("sentinel_notif")

-- Note from Synk fixed up sentinel and made the source not ass. enjoy ! please use proper formatting when programming ...
function sentinel.Broadcast(msg)
    sentinel.LastAlert = sentinel.LastAlert or CurTime()
    sentinel.NumberOfAlerts = sentinel.NumberOfAlerts or 1
    if sentinel.NumberOfAlerts > 5 and sentinel.LastAlert + 3 > CurTime() then return end

    if sentinel.LastAlert + 3 < CurTime() then
        sentinel.NumberOfAlerts = 1
        sentinel.LastAlert = CurTime()
    end

    if not msg then return end
    net.Start("sentinelBroadcast")
    net.WriteString(msg)
    net.Broadcast()
    sentinel.NumberOfAlerts = sentinel.NumberOfAlerts + 1
end

local priv = {
    ["Name"] = "sentinel_ignore",
    ["MinAccess"] = "admin"
}

CAMI.RegisterPrivilege(priv)

function sentinel.PermissionCheck(ply)
    if ply.sentinelignore then return true end

    if sam then
        if ply:HasPermission("sentinel_ignore") then return true end
    end

    if ply.sentinelignore == false then return false end

    CAMI.PlayerHasAccess(ply, "sentinel_ignore", function(b, _)
        if not IsValid(ply) then return end

        if b then
            ply.sentinelignore = true
        else
            ply.sentinelignore = false
        end
    end)
end


local systime = SysTime()

-- 8/29/2021
-- faketick from 50 to 69
-- For the new lag detection, if this triggers, its an immediate red flag telling the server that it just froze for a second
local function lagdetection()
    -- engine.ServerFrameTime does not work because it is clientside, So we're just gonna use FrameTime
    -- Also unfortunately you should not SPEED or SLOW down the game... If its either by host_timescale command or lua because well you know...
    -- It's gonna break the lag detection system, thinking the server is lagging when it actually isn't
    -- It's also gonna set the lag_counter up way too fast. maybe even starting an admin cleanup within seconds, causing everyone to be very upset that they lost their progress since the game was sped up
    local tick = engine.TickInterval() / (SysTime() - systime)
    local fake_tick = 1 / tick
    systime = SysTime()
    major_lag_detected = 0

    -- No need too debug. this is the final one and i don't want it to spam the console every 1 second saying the tick and the lag_counter
    if fake_tick > 150 then
        -- set phys_Timescale to 0
        disablephysics = 1
        disablephysics = 1
        disablephysics = 1

        timer.Create("turnitbackonthephysv2_3", 6, 1, function()
            disablephysics = 0
        end)


local localdumbass = spawnedentityuser
-- RunConsoleCommand("ulx","freeze","" .. localdumbass .. "")
-- timer.Create("Sentinel_unfreezethisdude", 16, 1, function() RunConsoleCommand("ulx","unfreeze","*") localdumbass = 0 end)
-- PrintMessage(HUD_PRINTTALK, "[Sentinel]: " .. localdumbass .. " has been frozen because of latest entity spawn. will expire in 16 seconds")
--libby_date = os.date()
------data = file.Read("Sentinelmonitorization.txt") if ( data ) then file.Append( "Sentinelmonitorization.txt", "\r\n [Sentinel]: " .. localdumbass .. " has been frozen for temp (major lag detected latest entity spawn)") end
        --
        if interactionuser == 0 then
            PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] No user has interacted with something yet")
        else
        end

        --RunConsoleCommand("ulx","freeze","" .. interactionuser .. "")
        --timer.Create("Sentinel_unfreezethisdude_interactionuser", 30, 1, function() RunConsoleCommand("ulx","unfreeze","*") end)
        --timer.Simple(0.1, function() PrintMessage(HUD_PRINTTALK, "[Sentinel]: " .. interactionuser .. " has been frozen because of suspicious activity (major lag and user unfroze). will expire in 30 seconds") end)
        --RunConsoleCommand("ulx","sendlua","" .. interactionuser .. "","chat.AddText( Color( 33, 255, 0 ), '[Sentinel]', Color( 255, 255, 255 ), ' Sentinel to you: You are frozen because you unfreezed something and the server detected measureable lag' )")
        --libby_date = os.date()
        ------data = file.Read("Sentinelmonitorization.txt") if ( data ) then file.Append( "Sentinelmonitorization.txt", "\r\n [Sentinel]: " .. localdumbass .. " has been frozen for temp (lag detected physgun interactions unfreeze)") end
        if duplicatorusernick == 0 then
            PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] No user has used a duplicator tool since the last 8 seconds")
        else
        end

        --RunConsoleCommand("ulx","freeze","" .. duplicatorusernick .. "")
        --timer.Create("Sentinel_unfreezethisdude_interactionuser", 30, 1, function() RunConsoleCommand("ulx","unfreeze","*") end)
        --timer.Simple(0.1, function() if duplicatorusernick == 0 then PrintMessage( HUD_PRINTCONSOLE, "[Sentinel] No user has used a duplicator tool since the last 8 seconds") else PrintMessage(HUD_PRINTTALK, "[Sentinel]: " .. duplicatorusernick .. " (major lag) duplicator equals freeze. will expire in 30 seconds") end end)
        --libby_date = os.date()
        ------data = file.Read("Sentinelmonitorization.txt") if ( data ) then file.Append( "Sentinelmonitorization.txt", "\r\n [Sentinel]: " .. localdumbass .. " has been frozen for temp (lag detected physgun interactions unfreeze)") end
        local localfaggot = localretard
        --RunConsoleCommand("ulx","freeze","" .. localfaggot .. "")
        --timer.Create("Sentinel_unfreezethisdude_majorlag", 15, 1, function() RunConsoleCommand("ulx","unfreeze","*") localfaggot = 0 end)
        --RunConsoleCommand("ulx","sendlua","" .. localfaggot .. "","chat.AddText( Color( 33, 255, 0 ), '[Sentinel]', Color( 255, 255, 255 ), ' Sentinel to you: You are frozen because major lag was detected and you were the last person to spawn an entity.' )")
        --libby_date = os.date()
        ------data = file.Read("Sentinelmonitorization.txt") if ( data ) then file.Append( "Sentinelmonitorization.txt", "\r\n [Sentinel]: " .. localfaggot .. " has been frozen for temp (major lag detected latest entity spawn)") end
        major_lag_detected = 1
        lag_counter = lag_counter + 1
        lag_freeze_counter = lag_freeze_counter + 1
        time_since_lag = time_since_lag + 0.1
        --print("[Sentinel] debug: lag intensity at " .. fake_tick .. "%. lag counter = " .. lag_counter .. ". time since lag started: " .. time_since_lag .. "")
        --print("[Sentinel] debug: It appears the server has froze for a second, is someone trying to crash the server?")
        --PrintMessage(HUD_PRINTTALK, "[Sentinel]: major lag detected, intensity: " .. fake_tick .. "")
        sentinel.Broadcast("⚠ LARGE AMOUNTS OF LAG DETECTED (" .. fake_tick .. "%) ⚠")
        --RunConsoleCommand("gmod_admin_cleanup","ropeconstraints") -- Somehow you can lag the server just by having a shitload of ropes. so thanks!
        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(3)
                        end
                    else
                    end
                    ----print("[Sentinel]: This dumbshit entity has no physics!")
                end
            end
        end

        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
        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", 6, 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, 4, function()
            nophysics = 1
            nophysics = 1
            disablephysics = 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
        -- Notify peasants lag prevention payload has executed
        sentinel.Broadcast("⚠ intensive major 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
            local 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

--[[
                sentinel.Broadcast(ply:Nick() .. " 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(8, 5)
                net.Send(ply)
                net.Start("sentinel_frozen")
                net.Send(ply)
]]--
            end

            -- Unfreeze them
            timer.Create("sentinel_unfreezebroo", 10, 1, function()
                sentinel.Broadcast("[Sentinel] Unfroze all players")

                for k, v in pairs(player.GetAll()) do
                    v:UnLock()
                end
            end)
        end
        --[[
-- wow, even too many explosions can cause lag! delete all env_explosion
libre_haltexplosions()
libre_haltexplosions2()
libre_haltexplosions3()
libre_haltexplosions4()
]]
        --
        ----print("[Sentinel] debug: lag exists")
    elseif fake_tick > 69 then
        lag_counter = lag_counter + 3
        time_since_lag = time_since_lag + 0.1
        --print("[Sentinel] debug: lag intensity over 32%? intensity: " .. fake_tick .. " Add +3 to the lag_counter, lag_counter = " .. lag_counter .. "")
        -- set phys_Timescale to 0
        disablephysics = 1
        disablephysics = 1
        disablephysics = 1

        timer.Create("turnitbackonthephysv2_3", 6, 1, function()
            disablephysics = 0
        end)
    else --libby_date = os.date() ------data = file.Read("libbylagpreventionlog.txt") if ( data ) then file.Append( "libbylagpreventionlog.txt", "\r\n [libby_lag_prevention_log]: Lag intensity over 32% (server froze for a second) intensity: " .. fake_tick .. "      Time: " .. libby_date .. "" ) end
        lag_counter = lag_counter - 1
        time_since_lag = 0
        ----print("tick at " .. fake_tick .. "")
        ----print("lag counter: " .. lag_counter .. "")
        ----print("lag does not exist")
    end
end

timer.Create("lagdetection", 0.1, 0, lagdetection)

local function lagdetection_33()
    -- incase smh 
    -- I have this code here just incase the tick just happens to drop low way too fast
    local tick = engine.TickInterval() / (SysTime() - systime)
    local fake_tick = 1 / tick
    systime = SysTime()

    -- No need too debug. this is the final one and i don't want it to spam the console every 1 second saying the tick and the lag_counter
    if fake_tick > 50 then
        lag_counter = lag_counter + 1
        time_since_lag = time_since_lag + 0.15
        --print("[Sentinel] debug: lag intensity over 32%? intensity: " .. fake_tick .. " Add +1 to the lag_counter, lag_counter = " .. lag_counter .. "")
        --libby_date = os.date()
        ------data = file.Read("libbylagpreventionlog.txt") if ( data ) then file.Append( "libbylagpreventionlog.txt", "\r\n [libby_lag_prevention_log]: Lag intensity over 32% (server froze for a second) intensity: " .. fake_tick .. "      Time: " .. libby_date .. "" ) end
    else
    end
    ----print("???")
end

timer.Create("lagdetection_33", 0.25, 0, lagdetection_33)

timer.Create("negativenumbersarebad", 0, 0, function()
    if lag_counter < 0 then
        lag_counter = lag_counter + 1
    end
end)

-- concommand shit to reload script easier instead of having to wait 24 seconds for it to update itself and not type to run the script although i'm a fast typer
local watdafack = 0
watdafack = SysTime()

if watdafack < 60 then
else --print("[Sentinel]: The server probably crashed or map restarted. SysTime or server operating time in seconds is below 10") ------data = file.Read("Sentinelmonitorization.txt") if ( data ) then file.Append( "Sentinelmonitorization.txt", "\r\n ================================================================================================================") end --libby_date = os.date() ------data = file.Read("Sentinelmonitorization.txt") if ( data ) then file.Append( "Sentinelmonitorization.txt", "\r\n [Sentinel]: Aw crap! The server crashed? How could this happen? (CHECK THE LOGS ABOVE ME) --> " .. os.date() .. "") end ------data = file.Read("Sentinelmonitorization.txt") if ( data ) then file.Append( "Sentinelmonitorization.txt", "\r\n ================================================================================================================") end --libby_date = os.date() ------data = file.Read("libbylagpreventionlog.txt") if ( data ) then file.Append( "libbylagpreventionlog.txt", "\r\n [The script restarted automatically (Possibly a map change or Restart because of a server crash] " .. libby_date .. "") end --libby_date = os.date() ------data = file.Read("libbylagproplog.txt") if ( data ) then file.Append( "libbylagproplog.txt", "\r\n [The script restarted automatically (Possibly a map change or Restart because of a server crash] " .. libby_date .. "") end
end

--print("[Sentinel]: The SysTime is over 60! This means the server likely did not crash a while ago")
concommand.Add("libby_lag_reloadlag", function()
    -- This command stays hidden on clientside, but the only thing it does is reload the script, there are no exploits therefore it doesn't have to be admin only
    --print("[Sentinel]: Reloading lag prevention script...")
    timer.Simple(0.1, function()
        include("autorun/server/libby_lagstopper.lua")
    end)

    timer.Simple(0.2, function()
        include("autorun/server/libby_lagdetect.lua")
    end)

    timer.Simple(0.3, function()
        include("autorun/server/libre_antispam.lua")
    end)

    timer.Simple(0.4, function()
        include("autorun/server/libre_advdupe2.lua")
    end)

    --timer.Simple(0.5, function() RunConsoleCommand("ulx","runscript2","autorun/server/libre_advdupe_stackerfix.lua") end)
    timer.Simple(0.6, function()
        include("autorun/server/libby_sentinellagstat.lua")
    end)

    timer.Simple(0.7, function()
        include("autorun/server/libby_lagstopper2.lua")
    end)

    --print("[Sentinel]: reloaded manually by user.")
    sentinel.Broadcast("I am attempting to reload every single module of Sentinel.")
end)

libah_prop_counter = 0

concommand.Add("libby_lag_checkprop", function()
    libah_prop_counter = 0
    local ent = ents.FindByClass("prop_physics")

    for _, ent in pairs(ent) do
        if ent:IsValid() then
            libah_prop_counter = libah_prop_counter + 1
        end
    end

    timer.Create("libre_howmuchpropsinserver", 0.1, 1, function() end) --print("[Sentinel]: There are " .. libah_prop_counter .. " props present in the server.")
end)

-- also concommand shit to check lag for info
concommand.Add("libby_lag_checktick", function()
    local tick = engine.TickInterval() / (SysTime() - systime)
    local fake_tick = 1 / tick
    systime = SysTime()
end)

--print(" [Sentinel]: fake_tick = " .. fake_tick .. ". lag_counter = " .. lag_counter .. "")
-- ehhhhhhhhhh set all prop velocity cmd
concommand.Add("libby_lag_setvelocityprop", function()
    timer.Create("libby_justsetallpropsvelocityto050timeswhenyoujustdetectlag", 0, 50, function()
        local Entpleasestop = ents.FindByClass("prop_physics")

        for _, Entpleasestop in pairs(Entpleasestop) do
            if Entpleasestop:IsValid() then
                local physwtfstop = Entpleasestop:GetPhysicsObject()
                physwtfstop:SetVelocity(Vector(0.01, 0.01, 0.01))
                physwtfstop:SetVelocity(Vector(0.01, 0.01, 0.01))
            end
        end
    end)
end)

concommand.Add("libby_lag_sleepprops", function() end) --timer.Create("libby_sendthemsleeping", 0, 100, function() local Entsleepnow =  ents.FindByClass("prop_physics") for _,Entsleepnow in pairs(Entsleepnow) do if Entsleepnow:IsValid() then local phystimetosleep = Entsleepnow:GetPhysicsObject() phystimetosleep:Sleep() end end end)
-- help and stuff
concommand.Add("libby_lag_help", function() end) --print("Hello, this is libre's own lag protection!") --print("If you're not lenn, i don't know how you found this command") --print("Maybe you just check source code of our lag protection, but!") --print("Here, i'll list you the commands we have for now") --print("libby_lag_help (info)") --print("libby_lag_checktick (checks if server lagging)") --print("libby_lag_freezeall (freezes all entities to prevent lag)") --print("libby_lag_reloadlag (reloads script)") --print("libby_lag_checkprop (checks how many props present in server)") --print("libby_lag_setvelocityprop (sets all prop velocity to 0)") --print("libby_lag_sleepprops (sets all props to be frozen unti collided or something")

-- For some reason this code did not work perfectly on AnarchyBOT's source code so i'm just gonna do this
-- Yuh i need to check some lag bro!
hook.Add("PlayerSay", "AnarchyBOT_checklag", function(v, text, team)
    if string.find(string.lower(text), "!checklag") then
        if text[1] == "!" then
            if timer.Exists("checklag_delay") then
                timer.Simple(0.5, function()
                    RunConsoleCommand("ulx", "tsay", "AnarchyBOT: I just already told you the info! Wait 4 seconds")
                end)
            else
                --print("AnarchyBOT is now gathering information from lag_prevention...")
                local tick = engine.TickInterval() / (SysTime() - systime)
                local fake_tick = 1 / tick
                systime = SysTime()
                --print(" [Sentinel]: fake_tick = " .. fake_tick .. ". lag_counter = " .. lag_counter .. "")
                RunConsoleCommand("ulx", "tsay", "AnarchyBOT: Lag intensity is about " .. fake_tick .. "%. lag_counter = " .. lag_counter .. "")
                RunConsoleCommand("ulx", "tsay", "AnarchyBOT: If lag intensity is about 10% or higher, there is obviously lag")
                timer.Create("checklag_delay", 1, 4, function() end)
            end
        end
    end
end)

-- how much times has the lag-prevention detect lag? I wonder.
hook.Add("PlayerSay", "AnarchyBOT_checkhowmanytimeslagdetected", function(v, text, team)
    if string.find(string.lower(text), "!counterlag") then
        if text[1] == "!" then
            if timer.Exists("AnarchyBOT_lagcounterdelay") then
                timer.Simple(0.5, function()
                    RunConsoleCommand("ulx", "tsay", "AnarchyBOT: I just already told you the info! Wait 4 seconds")
                end)
            else
                --print("AnarchyBOT is now gathering information from lag_prevention...")
                local tick = engine.TickInterval() / (SysTime() - systime)
                local fake_tick = 1 / tick
                systime = SysTime()
                --print(" [Sentinel]: lag_counter = " .. lag_counter .. "")
                RunConsoleCommand("ulx", "tsay", "AnarchyBOT: Lag was detected about " .. lag_detected_times .. " times.")
                timer.Create("AnarchyBOT_lagcounterdelay", 1, 4, function() end)
            end
        end
    end
end)



concommand.Add("libby_lag_freezeall", function()
    ----print("[Sentinel]: Freeze everything you dumb shit")
    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
                    --entityfroze = entityfroze + 1                             
                    phys:EnableMotion(false)
                end

                if not ent:IsPlayer() then end -- only needed when i need it --//ent:SetCollisionGroup(COLLISION_GROUP_INTERACTIVE_DEBRIS )
                if ent:IsPlayer() then end ----print("this entity is a player")
            else
            end
            ----print("[Sentinel]: This dumbshit entity has no physics!")
        end
    end
end)

entityfound = 0
entityfroze = 0

concommand.Add("libby_lag_stats", function()
    timer.Create("libby_howmuchentitiesfrozen", 0.5, 1, function()
        print("[Sentinel]: " .. entityfound .. " entities are present on the map,  " .. entityfroze .. " entities have been frozen")
        PrintMessage(HUD_PRINTTALK, "" .. entityfound .. " entities are present in this map.")
    end)

    timer.Create("libby_resetentitiescounter", 0.75, 1, function()
        entityfroze = 0
        entityfound = 0
    end)

    local ent = ents.FindByClass("*")

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

            if IsValid(phys) then
                if not ent:IsPlayer() then
                    entityfroze = entityfroze + 1
                end

                if ent:IsPlayer() then end
            else
            end
        end
    end
end)

spawnedeffect = 0
spawnednpc = 0
spawnedragdoll = 0
spawnedsent = 0
spawnedswep = 0
spawnedvehicle = 0
spawnedentityuser = 0

-- required it's also an anti-crash thingy
hook.Add("PlayerSpawnedEffect", "Sentinel_spawnedstuff1", function(ply, ent, model)
    --print("[Sentinel] effect was spawned by " .. ply:Nick() .. "")
    --PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " spawned effect " .. ent:GetClass() .. " " .. ent:GetModel() .. "")
    spawnedentityuser = ply:Nick()

    timer.Create("nospawnedentityuser", 3, 1, function()
        spawnedentityuser = 0
    end)
end)

hook.Add("PlayerSpawnedNPC", "Sentinel_spawnedstuff2", function(ply, ent, model)
    --PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " spawned npc " .. ent:GetClass() .. "")

    --print("[Sentinel]: NPC was spawned by " .. ply:Nick() .. "")
    -- Objects that I like to shove up my ass
    -- Once said by an korean kpop girl ^
    -- npc_antlionguard, npc_helicopter, npc_combinegunship, npc_strider, monster_nihilanth, gmod_wire_gimbal, npc_fastzombie, gmod_wire_expression2, gmod_wire_explosive, gmod_wire_simple_explosive, monster_gargantua, monster_bigmomma
    if ent:GetClass() == "npc_helicopter" or ent:GetClass() == "npc_combinegunship" or ent:GetClass() == "npc_strider" or ent:GetClass() == "gmod_wire_expression2" or ent:GetClass() == "gmod_wire_gimbal" or ent:GetClass() == "monster_gargantua" or ent:GetClass() == "monster_bigmomma" or ent:GetClass() == "monster_nihilanth" or ent:GetClass() == "npc_combinedropship" then
        ent:Remove()
    end

    spawnedentityuser = ply:Nick()

    timer.Create("nospawnedentityuser", 3, 1, function()
        spawnedentityuser = 0
    end)
end)

hook.Add("PlayerSpawnedRagdoll", "Sentinel_spawnedstuff3", function(ply, model, ent)
    --PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " spawned ragdoll " .. ent:GetModel() .. "")
    --print("[Sentinel]: Ragdoll was spawned by " .. ply:Nick() .. "")
    spawnedentityuser = ply:Nick()

    timer.Create("nospawnedentityuser", 3, 1, function()
        spawnedentityuser = 0
    end)
end)

hook.Add("PlayerSpawnedSENT", "Sentinel_spawnedstuff4", function(ply, ent, model)
    --PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " spawned sent " .. ent:GetClass() .. "")

    -- Libby's Sandbox/Playground buildmode kill prevention with dronesrewrite
    if ent:GetClass() == "dronesrewrite_upgrcase_ai_attack" then
        if ply:GetNWBool("BuildMode", false) then
            PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] " .. ply:Nick() .. " is not permitted to spawn the AI attack from dronesrewrite due to an exploit")
            ent:Remove()
            ply:SendLua("chat.AddText('[Sentinel]: Cannot spawn a dronesrewrite AI Attack because you are in buildmode')")
        end
    end

    spawnedentityuser = ply:Nick()

    timer.Create("nospawnedentityuser", 3, 1, function()
        spawnedentityuser = 0
    end)
end)

-- PlayerGiveSWEP
hook.Add("PlayerSpawnedSWEP", "Sentinel_spawnedstuff5", function(ply, ent, model)
    --[[
weapon_v6lenn_do_a_barrel_roll
weapon_v2lenn_the_haxx
weapon_v2lenn_o'l_mighty_potato_king_of_lenn
weapon_v4lenn_rock_thrower_throw_rocks
weapon_v6lenn_the_bible
weapon_v2lenn_when_life_gives_you_melons_you_make_cake
weapon_v7lenn_sawblade
]]
    --
    --[[
if ent:GetClass() == "weapon_v6lenn_do_a_barrel_roll" or ent:GetClass() == "weapon_v2lenn_the_haxx" or ent:GetClass() == "weapon_v2lenn_o'l_mighty_potato_king_of_lenn" or ent:GetClass() == "weapon_v4lenn_rock_thrower_throw_rocks" or ent:GetClass() == "weapon_v6lenn_the_bible" or ent:GetClass() == "weapon_v2lenn_when_life_gives_you_melons_you_make_cake" or ent:GetClass() == "weapon_v7lenn_sawblade" then
--PrintMessage( HUD_PRINTCONSOLE, "[Sentinel] " .. ply:Nick() .. " spawned a lenn projectile weapon") 
if ply:GetNWBool( "BuildMode", false ) then
--PrintMessage( HUD_PRINTCONSOLE, "[Sentinel] " .. ply:Nick() .. " is not permitted to spawn these weapons in build mode") 
ply:SendLua("chat.AddText('[Sentinel]: Cannot spawn this weapon because you are in buildmode')")
return false 
end
end
]]
    --
    --PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " gave/spawn swep " .. ent:GetClass() .. "")
    print("[Sentinel]: swep was spawned by " .. ply:Nick() .. " with a tool")
    spawnedentityuser = ply:Nick()

    timer.Create("nospawnedentityuser", 3, 1, function()
        spawnedentityuser = 0
    end)

    entclassswep = ent:GetClass()
end)

hook.Add("PlayerSpawnedVehicle", "Sentinel_spawnedstuff6", function(ply, ent, model)
    requirevehicleclass = ent:GetClass()
    --PrintMessage( HUD_PRINTCONSOLE, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " spawned vehicle " .. ent:GetClass() .. "")
    --print("[Sentinel]: vehicle was spawned by " .. ply:Nick() .. "")
    spawnedentityuser = ply:Nick()
end)

hook.Add("PlayerSpawnedProp", "Sentinel_spawnedstuffpropcommon", function(ply, model, ent)
    if ent:GetCollisionGroup() == "1" then
        --ent:SetCollisionGroup(COLLISION_GROUP_DEBRIS)
    else
        --ent:SetCollisionGroup(COLLISION_GROUP_INTERACTIVE_DEBRIS)
    end
    spawnedentityuser = ply:Nick()
    --PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " spawned prop " .. ent:GetModel() .. "")

    if retardalert == 1 then
        PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " <-- gay intruder (prop)")
         if sentinel.PermissionCheck(ply) then
              sentinel.Broadcast(ply:Nick() .. " was spared from being frozen due to having the permission :(")

              return
         end

          ply:Lock()
          sentinel.Broadcast(ply:Nick() .. " has been frozen [TYPE: PROP SPAWN]")
          net.Start("sentinel_notif")
          net.WriteString("Sentinel froze you to make sure you aren't causing lag!")
          net.WriteInt(NOTIFY_ERROR, 5)
          net.WriteInt(8, 5)
          net.Send(ply)
          net.Start("sentinel_frozen")
          net.Send(ply)


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

            //sentinel.Broadcast("All players have been unfrozen")
        end)

        --potentialservercrasher = 0
        --abnormallagactivity2 = 0
        retardalert = 0
    end

    if abnormallagactivity2 > 10 then
        --PrintMessage( HUD_PRINTCONSOLE, "[Sentinel] abnormallagactivity2 hit over 1, let us see who's crashing the server?")
        PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " is suspicious")
        potentialservercrasher = potentialservercrasher + 1

        timer.Create("nolongermarkedascrasher", 0.32, 1, function()
            potentialservercrasher = 0
        end)

        if potentialservercrasher > 8.01 then
            ply = player.GetBySteamID(spawnedentityuser)
            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

--[[
                ply:Lock()
                sentinel.Broadcast(ply:Nick() .. " has been frozen [TYPE: PROP SPAWN 2]")
                net.Start("sentinel_notif")
                net.WriteString("Sentinel froze you to make sure you aren't causing lag!")
                net.WriteInt(NOTIFY_ERROR, 5)
                net.WriteInt(8, 5)
                net.Send(ply)
                net.Start("sentinel_frozen")
                net.Send(ply)
]]--
            end

            timer.Create("sentinel_unfreezemeplease", 10, 1, function()
                for k, v in pairs(player.GetAll()) do
                    v:UnLock()
                end

                //sentinel.Broadcast("All players have been unfrozen")
            end)

            potentialservercrasher = 0
            abnormallagactivity2 = 0
        end
    end
end)

-- Yes.
function libre_checkentsphysic(ent)
    local ent = ents.FindByClass("prop_physics")

    for _, ent in pairs(ent) do
        local pos = ent:GetPos()
        local propsnear = ents.FindInSphere(pos, 0.22)
        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 > 24 then
                    retardalert = 1

                    timer.Create("retardalertisover", 0.5, 1, function()
                        retardalert = 0
                    end)

                    --PrintMessage(HUD_PRINTCONSOLE, "[Sentinel]: " .. ent:GetModel() .. " removed :) (physics) (checkents)") This causes a reliable channel overflow took me hours to find -- Synk
                    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
                --     RunConsoleCommand("ulx", "notifications", "*", "[libby_lag_prevention]: Thanks, (anti_stacker_preventions_executed)", "generic", "6")

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

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

hook.Add("OnPhysgunFreeze", "Sentinel_interactions1", function(weapon, physobj, ent, ply)
    if ent:IsValid() then
        --//ent:SetCollisionGroup(COLLISION_GROUP_DEBRIS)
        -- Well uhh decided to make a thing to like find out who's trying to crash the server
        -- Requires sentinellagstat.lua
        if abnormallagactivity2 > 10 then
            --PrintMessage( HUD_PRINTCONSOLE, "[Sentinel] abnormallagactivity2 hit over 1, let us see who's crashing the server?")
            PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " is suspicious")
            potentialservercrasher = potentialservercrasher + 1

            timer.Create("nolongermarkedascrasher", 0.32, 1, function()
                potentialservercrasher = 0
            end)


// insane!
            if potentialservercrasher > 5.01 then
                --PrintMessage( HUD_PRINTTALK, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " has been frozen [TYPE:  ")
                if IsValid(player.GetBySteamID(duplicatorusernick)) then
                    if sentinel.PermissionCheck(ply) then
                        sentinel.Broadcast(ply:Nick() .. " was spared from being frozen due to having the permission :(")

                        return
                    end

--[[
                    ply:Lock()
                    sentinel.Broadcast(ply:Nick() .. " has been frozen [TYPE: PHYSGUN FREEZE]")
                    net.Start("sentinel_notif")
                    net.WriteString("Sentinel froze you to make sure you aren't causing lag!")
                    net.WriteInt(NOTIFY_ERROR, 5)
                    net.WriteInt(8, 5)
                    net.Send(ply)
                    net.Start("sentinel_frozen")
                    net.Send(ply)
]]--
                end

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

                    //sentinel.Broadcast("All players have been unfrozen")
                end)

                potentialservercrasher = 0
                abnormallagactivity2 = 0
            end
        end

        --libre_checkwheelstacked()
        --//ent:SetCollisionGroup(COLLISION_GROUP_NONE)
        --PrintMessage( HUD_PRINTCONSOLE, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " physgun interaction OnPhysgunFreeze (froze something)")
        --BroadcastLua( "print( '[Sentinel] Physics gun interaction. Set collision group to: Normal' )" )
        --print("[Sentinel]: " .. ply:Nick() .. " physgun freeze interaction")
        suspicioususer = ply:Nick()
        physgunuser = ply:Nick()

        timer.Create("Sentinel_aodfkiutneraction", 0.75, 1, function()
            suspicioususer = 0
        end)
    end
end)

lastpickupuser = 0

hook.Add("OnPhysgunPickup", "Sentinel_interactions2", function(ply, ent)
    if ent:IsValid() then
        libre_checkentsphysic()
        if retardalert == 1 then
            PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " <-- gay intruder (physgun)")

            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

                ply:Lock()
                sentinel.Broadcast(ply:Nick() .. " has been frozen [TYPE: PHYSGUN PICKUP]")
                net.Start("sentinel_notif")
                net.WriteString("Sentinel froze you to make sure you aren't causing lag!")
                net.WriteInt(NOTIFY_ERROR, 5)
                net.WriteInt(8, 5)
                net.Send(ply)
                net.Start("sentinel_frozen")
                net.Send(ply)
            end

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

                //sentinel.Broadcast("All players have been unfrozen")
            end)

            potentialservercrasher = 0
            abnormallagactivity2 = 0
            retardalert = 0
        end

        --//ent:SetCollisionGroup(COLLISION_GROUP_DEBRIS)
        --libre_checkwheelstacked()
        -- Well uhh decided to make a thing to like find out who's trying to crash the server
        -- Requires sentinellagstat.lua
        if abnormallagactivity2 > 10 then
            --PrintMessage( HUD_PRINTCONSOLE, "[Sentinel] abnormallagactivity2 hit over 1, let us see who's crashing the server?")
            PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " is suspicious")
            potentialservercrasher = potentialservercrasher + 1

            timer.Create("nolongermarkedascrasher", 0.32, 1, function()
                potentialservercrasher = 0
            end)

            if potentialservercrasher > 10 then
                --PrintMessage( HUD_PRINTTALK, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " has been frozen [TYPE: PHYSGUN PICKUP 2]")
                if sentinel.PermissionCheck(ply) then
                    sentinel.Broadcast(ply:Nick() .. " was spared from being frozen due to having the permission :(")

                    return
                end

--[[
                ply:Lock()
                sentinel.Broadcast(ply:Nick() .. " Has been frozen [TYPE PHYSGUN PICKUP 2]")
                net.Start("sentinel_notif")
                net.WriteString("Sentinel froze you to make sure you aren't causing lag!")
                net.WriteInt(NOTIFY_ERROR, 5)
                net.WriteInt(8, 5)
                net.Send(ply)
                net.Start("sentinel_frozen")
                net.Send(ply)
]]--

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

                    //sentinel.Broadcast("All players have been unfrozen")
                end)



                potentialservercrasher = 0
                abnormallagactivity2 = 0
            end
            local constrained = constraint.GetAllConstrainedEntities(ent)
            local unfrozenpickup = 0
            for _, v in pairs(constrained) do
                local phys = v:GetPhysicsObject()
                if IsValid(phys) then
                    if phys:IsMotionEnabled() then
                        unfrozenpickup = unfrozenpickup + 1
                    end
                end
            end
            if unfrozenpickup > 30 then
                if sentinel.PermissionCheck(ply) then
                    sentinel.Broadcast(ply:Nick() .. " was spared from being frozen due to having the permission :(")

                    return
                end

--[[
                ply:Lock()
                sentinel.Broadcast(ply:Nick() .. " Has been frozen [TYPE PHYSGUN PICKUP 3] ")
                net.Start("sentinel_notif")
                net.WriteString("Sentinel froze you to make sure you aren't causing lag!")
                net.WriteInt(NOTIFY_ERROR, 5)
                net.WriteInt(8, 5)
                net.Send(ply)
                net.Start("sentinel_frozen")
                net.Send(ply)
]]--

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

                    //sentinel.Broadcast("All players have been unfrozen")
                end)
            end
        end

        if ent:GetModel() == "models/props_phx/construct/metal_plate_curve360x2.mdl" or ent:GetModel() == "models/props_phx/misc/potato_launcher_chamber.mdl" then
            PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] entirely ghosted illegal prop " .. ent:GetModel() .. " by " .. ply:Nick() .. " after physgun pickup")
            --ent:SetCollisionGroup(COLLISION_GROUP_DEBRIS)
        end

        --PrintMessage( HUD_PRINTCONSOLE, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " physgun interaction OnPhysgunPickup (pick something up)")
        --BroadcastLua( "print( '[Sentinel] Physics gun interaction. Set collision group to: Normal' )" )
        --print("[Sentinel]: " .. ply:Nick() .. " physgun pickup interaction")
        suspicioususer = ply:Nick()
        physgunuser = ply:Nick()

        timer.Create("Sentinel_aodfkiutneraction", 0.75, 1, function()
            suspicioususer = 0
        end)
    end
end)

hook.Add("PhysgunDrop", "Sentinel_interactions4", function(ply, ent)
    --PrintMessage( HUD_PRINTCONSOLE, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " physgun interaction PhysgunDrop (unfreeze or drop)")
    --//ent:SetCollisionGroup(COLLISION_GROUP_DEBRIS)
    if abnormallagactivity2 > 10 then
        --PrintMessage( HUD_PRINTCONSOLE, "[Sentinel] abnormallagactivity2 hit over 1, let us see who's crashing the server?")
        PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " is suspicious")
        potentialservercrasher = potentialservercrasher + 1

        timer.Create("nolongermarkedascrasher", 0.32, 1, function()
            potentialservercrasher = 0
        end)

        if potentialservercrasher > 10.01 then
            --PrintMessage( HUD_PRINTTALK, "[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " has been frozen [TYPE: PHYSGUN DROP]")
            if sentinel.PermissionCheck(ply) then
                sentinel.Broadcast(ply:Nick() .. " was spared from being frozen due to having the permission :(")

                return
            end

--[[
            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(8, 5)
            net.Send(ply)
            net.Start("sentinel_frozen")
            net.Send(ply)
            sentinel.Broadcast(ply:Nick() .. " was frozen for being suspicous")
]]--

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

                //sentinel.Broadcast("All players have been unfrozen")
            end)

            potentialservercrasher = 0
            abnormallagactivity2 = 0
        end
    end

    if ent:IsValid() then end --print("[Sentinel] [" .. ply:SteamID() .. "] " .. ply:Nick() .. " physgun drop interaction")
end)

------data = file.Read("Sentinelmonitorization.txt") if ( data ) then file.Append( "Sentinelmonitorization.txt", "\r\n ================================================================================================================") end
--libby_date = os.date()
------data = file.Read("Sentinelmonitorization.txt") if ( data ) then file.Append( "Sentinelmonitorization.txt", "\r\n [Sentinel]: Sentinels main lag prevention system core appears to have been reloaded") end
------data = file.Read("Sentinelmonitorization.txt") if ( data ) then file.Append( "Sentinelmonitorization.txt", "\r\n ================================================================================================================") end
sentinel.Broadcast("Main lag prevention core successfully loaded!")

-- :)
-- This secret epic code by lenn will stay here for a while. it's pretty funny
-- Sorry if any of the administrators see this
--RunConsoleCommand("sv_use_steam_voice","1")
--timer.Create("lenn_voicecodec_hasbeenfucked_week", 3, 0, function() RunConsoleCommand("sv_use_steam_voice","0") timer.Simple(0.25, function()RunConsoleCommand("sv_use_steam_voice","1") end) end)
-- Fading door crash exploit fix
function libre_fadingdoorcheck(ent)
    local ent = ents.FindByClass("prop_physics")

    for _, ent in pairs(ent) do
        local pos = ent:GetPos()
        local propsnear = ents.FindInSphere(pos, 0.2)
        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 > 20.1 then
                    retardalert = 1

                    timer.Create("retardalertisover", 0.5, 1, function()
                        retardalert = 0
                    end)

                    PrintMessage(HUD_PRINTCONSOLE, "[Sentinel]: " .. ent:GetModel() .. " was removed due to being a suspicious entity. (fading door check)")
                    ent:Remove()
                    stackent = 0
                    timer.Create("libre_warnings", 0.1, 1, function() end) --for _, v in ipairs(player.GetHumans()) do --v:SendLua([[chat.AddText( Color( 33, 255, 0 ), "[Sentinel]", Color( 255, 255, 255 ), " suspicious entities detected during fading door, removing" )]]); --end

                    timer.Create("libre_warnsuspiciousentities", 0.25, 1, function()
                        PrintMessage(HUD_PRINTTALK, "[Sentinel]: (fading door) deleted " .. 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 end --ent:SetCollisionGroup(COLLISION_GROUP_WORLD)
                --         end
                --     end)
                -- end
            end
        end
        --end
    end
end

local function fadeActivate(self)
    PrintMessage(HUD_PRINTCONSOLE, "Fading door activate called")
    libre_fadingdoorcheck()
    if self.fadeActive then return end
    self.fadeActive = true
    self.fadeMaterial = self:GetMaterial()
    self.fadeDoorMaterial = self.fadeDoorMaterial or "sprites/heatwave"
    self:SetMaterial(self.fadeDoorMaterial)
    self:DrawShadow(false)

    if self.fadeCanDisableMotion then
        --self:SetNotSolid(true)
    else
        --self:SetCollisionGroup(COLLISION_GROUP_WORLD)
    end

    local phys = self:GetPhysicsObject()

    if IsValid(phys) then
        PrintMessage(HUD_PRINTCONSOLE, "Fading door activate called")
        self.fadeMoveable = phys:IsMoveable()
        phys:EnableMotion(false)
    end

    if self.fadeDoorOpenSound and Sounds and Sounds[self.fadeDoorOpenSound] then
        self:EmitSound(Sounds[self.fadeDoorOpenSound], 350, 100)
    end

    if self.fadeDoorLoopSound and LoopSounds and LoopSounds[self.fadeDoorLoopSound] and not self.FadeDoorSound then
        self.FadeDoorSound = CreateSound(self, LoopSounds[self.fadeDoorLoopSound])
        self.FadeDoorSound:Play()
    end

    if WireLib then
        Wire_TriggerOutput(self, "FadeActive", 1)
    end
end

local function fadeDeactivate(self)
    PrintMessage(HUD_PRINTCONSOLE, "Fading door activate called")
    libre_fadingdoorcheck()
    self.fadeActive = false

    if self:GetMaterial() == self.fadeDoorMaterial and self.fadeMaterial then
        self:SetMaterial(self.fadeMaterial)
    end

    self:DrawShadow(true)

    if self.fadeCanDisableMotion then
        self:SetNotSolid(false)
    else
        self:SetCollisionGroup(COLLISION_GROUP_NONE)
    end

    local phys = self:GetPhysicsObject()

    if IsValid(phys) then
        PrintMessage(HUD_PRINTCONSOLE, "Fading door activate called")
        phys:EnableMotion(self.fadeMoveable or false)
        phys:Wake()
    end

    if self.fadeDoorCloseSound and Sounds and Sounds[self.fadeDoorCloseSound] then
        self:EmitSound(Sounds[self.fadeDoorCloseSound], 350, 100)
    end

    if self.FadeDoorSound then
        self.FadeDoorSound:Stop()
    end

    self.FadeDoorSound = nil

    if WireLib then
        Wire_TriggerOutput(self, "FadeActive", 0)
    end
end

hook.Add("CanTool", "libre_checkfadingdoorexploit", function(ply, tr, tool)
    if tool == "fading_door" then
        --PrintMessage( HUD_PRINTCONSOLE, "[Sentinel]: [" .. ply:SteamID() .. "] " .. ply:Nick() .. " is using fading door tool. checking for suspicious entities")
        libre_fadingdoorcheck()
        local toolgun = ply:GetTool(CurrentTool)

        if toolgun:GetClientInfo("mat"):match("pp[\\/]copy") then
            sentinel.Broadcast("Kicked " .. ply:Nick() .. " for attempting the blackout exploit")
            ply:Kick("[Sentinel] Attempted blackout exploit.")

            return false
        end

        return true
    end
end)

sleepphysics = 0
physicsprop = 0
unfrozenphysics = 0
sentinellagpercent = 0
sentinelthing = 0

-- Even when physics don't move, they still (or could) be active, causing lag! so lets make them dormant
timer.Create("Sentinel_sleeppropskudasai", 30, 0, function()
    local ent = ents.FindByClass("prop_physics")

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

            if phys:IsValid() then
                physicsprop = physicsprop + 1

                if ent:IsValid() then
                    if phys:IsValid() then
                        --if phys:IsMotionEnabled() == true then
                        if phys:IsMoveable() then
                            unfrozenphysics = unfrozenphysics + 1
                        end
                    end

                    if phys:IsValid() then
                        if phys:IsPenetrating() then
                            sentinelthing = sentinelthing + 1
                        end
                    end

                    if ent:IsValid() then
                        if ent:GetVelocity():Length() < 0.5 then
                            if ent:IsValid() then
                                if phys:IsValid() then
                                    if phys:IsMotionEnabled() == true then
                                        if not phys:IsAsleep() then
                                            phys:Sleep()
                                            sleepphysics = sleepphysics + 1
                                        end
                                    end
                                end
                            end
                        end
                    end
                end
            end
        end
    end

    PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] " .. physicsprop .. " props online | " .. unfrozenphysics .. " are unfrozen | " .. sentinelthing .. " are penetrating | " .. sleepphysics .. " props put to sleep | expected lag percentage: " .. sentinellagpercent .. "%")
    sleepphysics = 0
    physicsprop = 0
    unfrozenphysics = 0
    sentinelthing = 0
end)

--[[
timer.Create("nologgingforulx", 10, 0, function()
    if not ulx then return end

//ulx.logString = function() return true end
//ulx.logString( string.format( "i hate niggers" ) )
//ulx.logWriteln = function() return true end
ulx.logSpawn = function() return true end

    hook.Remove("PlayerConnect", "ULXLogConnect")
    hook.Remove("PlayerInitialSpawn", "ULXLogInitialSpawn")
    hook.Remove("PlayerSay", "ULXLogSay")
    hook.Remove("PlayerDeath", "ULXLogDeath")
    hook.Remove("PlayerSpawnedNPC", "ULXLogNPCSpawn")
    hook.Remove("PlayerSpawnedSENT", "ULXLogSentSpawn")
    hook.Remove("PlayerSpawnedVehicle", "ULXLogVehicleSpawn")
    hook.Remove("PlayerSpawnedEffect", "ULXLogEffectSpawn")
    hook.Remove("PlayerSpawnedRagdoll", "ULXLogRagdollSpawn")
    hook.Remove("PlayerSpawnedProp", "ULXLogPropSpawn")
end)
]]--

timer.Simple(3, function()
    --sent_anti_noclip_control
    local ent = ents.FindByClass("sent_anti_noclip_control")

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

print("[Sentinel]: Main lag prevention core loaded successfully yes")
sentinel.Broadcast("Main lag core successfully reloaded")

-- We like this, thanks Synk!
-- COLLISION_GROUP_INTERACTIVE_DEBRIS	3	Collides with everything except other interactive debris or debris
-- COLLISION_GROUP_INTERACTIVE	4	Collides with everything except interactive debris or debris
local function sentinel_ghostent(ply, model, ent)
    if not ply:IsPlayer() then
        ent = ply
    elseif IsEntity(model) then
        ent = model
    end

    if not IsValid(ent) then return end
    if ent:CreatedByMap() then return end
    if string.match(ent:GetClass(), "lunasflightschool") then return end
    if string.match(ent:GetClass(), "func_") then return end

    if ent:IsNPC() and not ent:GetClass() == "npc_satchel" and not ent:GetClass() == "npc_grenade_frag" then
        return
    elseif ent:GetClass() == "npc_satchel" or ent:GetClass() == "npc_grenade_frag" then
        timer.Simple(0.05, function()
            if not IsValid(ent) then return end
            if ent:GetCollisionGroup() == 3 then return end
            --ent:SetCollisionGroup(3)
        end)

        return
    end

    if ent:IsWorld() then return end
    if ent:IsVehicle() then return end
    if ent:IsNPC() then return end
    --ent:SetCollisionGroup(3)
    --ent:CollisionRulesChanged()
end

hook.Add("OnEntityCreated", "sentinel_ghostretardedshit", sentinel_ghostent)
hook.Add("PlayerSpawnedSWEP", "sentinel_ghostretardedshit", sentinel_ghostent)

function widgets.PlayerTick()
end

hook.Remove("PlayerTick", "TickWidgets")

hook.Add("PreGamemodeLoaded", "widgets_disabler_cpu", function()
    MsgN("Disabling widgets...")

    function widgets.PlayerTick()
    end

    -- empty
    hook.Remove("PlayerTick", "TickWidgets")
    MsgN("Widgets disabled!")
end)

-- vehicles spam / vehicle lag patches
hook.Add("PlayerSpawnedVehicle", "sentinel_vehiclelagpatch", function(ply, ent, model)
    PrintMessage(HUD_PRINTCONSOLE, "[Sentinel] " .. ply:Nick() .. " spawned " .. ent:GetClass() .. " [" .. ent:GetModel() .. "]")

    if ent:GetClass() == "prop_vehicle_jeep" then
        local phys = ent:GetPhysicsObject()
        phys:EnableMotion(false)
    end
end)

// libbys can enable this instead
--[[
hook.Add("OnPhysgunReload", "sentinel_disableunfreezeall", function(weapon, ply)
    net.Start("sentinel_notif")
    net.WriteString("Physgun reload is disabled")
    net.WriteInt(NOTIFY_HINT, 5)
    net.WriteInt(1, 5)
    net.Send(ply)

    return false
end)
]]--

timer.Create("precision_alignsux", 10, 0, function()
    if util.NetworkStringToID( "precision_align_constraint" ) then
            net.Receive("precision_align_constraint", function(len,ply)
               	ply.sentinelprec = 1
                return
            end)
         print("[Sentinel] disabled constraints on precision alignment")
         timer.Remove("precision_alignsux")
    end
end)

hook.Add("PostGamemodeLoaded","shitnocollide", function()
    hook.Remove( "EntityRemoved", "nocollide_fix")
end)

--[[
local priv = {
    ["Name"] = "pac",
    ["MinAccess"] = "admin"
}
CAMI.RegisterPrivilege(priv)

function restrictPAC3(ply)
    if !ULib.ucl.query(ply,"pac") then
        if CLIENT then
            chat.AddText(Color(128,0,128), "[server] ", Color( 255,0,0), "Pac3 is restricted due to an exploit. Ask someone with perms to give you access")
        else
            ply:SendLua('chat.AddText(Color(128,0,128), "[server] ", Color( 255,0,0), "Pac3 is restricted due to an exploit. Ask someone with perms to give you access")')
        end
        return false
    end
end


hook.Add("PACApplyModel","PacRestrict", restrictPAC3)
hook.Add('PrePACConfigApply', 'SGRF - PAC3 Restriction', restrictPAC3)
hook.Add('PrePACEditorOpen', 'SGRF - PAC3 Restriction', restrictPAC3)
]]
--

--epic gaymer scottpott8 stuff

hook.Add("CanTool", "PreventDuplication", function(ply, trace, tool)
    if tool == "duplicator" and ply:KeyDown(IN_ATTACK2) then
        ply:ChatPrint("Please use Advanced Duplicator 2 to copy objects.")
        return false
    end
end)