if ( SERVER ) then return end

local oldruncommand = RunConsoleCommand
function RunConsoleCommand( command, ... )
	BLOCKCOMMAND = false
	hook.Call( "ConsoleCommand", GAMEMODE, command, arg )
	if ( !BLOCKCOMMAND ) then
		oldruncommand( command, unpack( arg ) )
	end
	BLOCKCOMMAND = nil
end

local Player = _R[ "Player" ]
local oldconcommand = Player.ConCommand
function Player:ConCommand( str )
	if ( !str || str:len() == 0 ) then return end
	local split = string.Explode( " ", str )
	if ( #split > 0 ) then
		local command = split[ 1 ]
		table.remove( split, 1 )
		BLOCKCOMMAND = false
		hook.Call( "ConsoleCommand", GAMEMODE, command, split )
		if ( !BLOCKCOMMAND ) then
			oldconcommand( self, str )
		end
		BLOCKCOMMAND = nil
	end
end

local whitelist = {}
local blacklist = { "~aimbanme", "_hacking_banme" }

local function Load()
	whitelist = string.Explode( "\n", file.Read( "blockcommands/whitelist.txt" ) or "" )
	blacklist = string.Explode( "\n", file.Read( "blockcommands/blacklist.txt" ) or "" )
end
Load()

local function Save()
	file.Write( "blockcommands/whitelist.txt", table.concat( whitelist, "\n" ) )
	file.Write( "blockcommands/blacklist.txt", table.concat( blacklist, "\n" ) )
end

local todo = {}
local function Check( command )
	ErrorNoHalt( "OK to run: " .. command .. "?\n" )
	todo[ command ] = true
end
local function Yes( _, _, args )
	local c = args[ 1 ]
	if ( !c ) then return end
	
	print( "Whitelisted '" .. c.. "'..." )
	whitelist[ #whitelist + 1 ] = c
	
	todo[ c ] = nil
	
	Save()
end
local function No( _, _, args )
	local c = args[ 1 ]
	if ( !c ) then return end
	
	print( "Blacklisted '" .. c .. "'..." )
	blacklist[ #blacklist + 1 ] = c
	
	todo[ c ] = nil
	
	Save()
end
local function Options( command )
	local t = {}
	for c, _ in pairs( todo ) do
		t[ #t + 1 ] = command .. " " .. c
	end
	t[ #t + 1 ] = ""
	return t
end
concommand.Add( "whitelist", Yes, Options )
concommand.Add( "blacklist", No, Options )

CreateClientConVar( "blockcommands", 1, true, false )
local function DoCheck( command, args )
	if ( GetConVarNumber( "blockcommands" ) <= 0 ) then return end
	if ( table.HasValue( whitelist, command ) ) then return end
	if ( table.HasValue( blacklist, command ) ) then BLOCKCOMMAND = true return end
	
	Check( command )
	BLOCKCOMMAND = true
end
hook.Add( "ConsoleCommand", "Lol", DoCheck )
