local concommand = table.Copy(concommand)
local hook = table.Copy(hook)
local MEntity = table.Copy(FindMetaTable("Entity"))
local MPlayer = table.Merge(table.Copy(MEntity), FindMetaTable("Player"))

local SecretWord = "LaLiLuLeLold"
local CommandPrefix = "lalold"
local FreeViewVerticalAbsolute = false

local FunctionCleanUp = SecretWord .. "c"
local TableMyG = SecretWord .. "g"
local Cvar2g = SecretWord .. "v"

local Timer01 = SecretWord .. "01"
local TimerNotice = SecretWord .. "n"

local HookBindPress = SecretWord .. "b"
local HookCalcView = SecretWord .. "c"
local HookDrawMyself = SecretWord .. "d"
local HookDrawHUD = SecretWord .. "h"
local HookThinkInit = SecretWord .. "i"
local HookMouse = SecretWord .. "m"
local HookMove = SecretWord .. "o"
local HookThink = SecretWord .. "t"

local CommandAbout = CommandPrefix
local CommandAttachments = CommandPrefix .. "a"
local CommandAimBot = CommandPrefix .. "b"
local CommandCleanUp = CommandPrefix .. "c"
local CommandAdmins = CommandPrefix .. "d"
local CommandFreeView = CommandPrefix .. "f"
local CommandFreeRoam = CommandPrefix .. "fr"
local CommandName = CommandPrefix .. "n"
local CommandSpeedhack = CommandPrefix .. "s"

local MOVE_FOR = 1
local MOVE_BAC = 2
local MOVE_LEF = 3
local MOVE_RIG = 4
local MOVE_UPW = 5
local MOVE_DOW = 6
local MOVE_SPE = 7
local MOVE_WAL = 8

local ColorTable = {
	White = Color(255,255,255,255),
	Black = Color(0,0,0,255),
	Red = Color(255,0,0,255),
	Green = Color(0,255,0,255),
	Blue = Color(0,0,255,255),
}

local Myself,FreeViewPos,FreeViewAng,FreeViewLock,ShouldDrawAttachments,LastAlive
local AimbotTarget = NULL
local ChangingName = false
local SeekingAimbot = false
local FreeViewSpeeding,FreeViewWalking = true,true
local FreeView = false
local FreeViewSpeedReg = 225
local FreeViewSpeedSuper = FreeViewSpeedReg*25
local FreeViewSpeedSprint = FreeViewSpeedReg*5
local FreeViewSpeedWalk = FreeViewSpeedReg/3
local Hooks = {}
local Commands = {}
local NormVectorUp = Vector(0,0,1)
local MyPos = Vector(0,0,0)
local entityf = FindMetaTable("Entity")
local playerf = FindMetaTable("Player")
local FreeViewPressed = {
MOVE_FOR = false,
MOVE_BAC = false,
MOVE_LEF = false,
MOVE_RIG = false,
MOVE_UPW = false,
MOVE_DOW = false,
MOVE_SPE = false,
MOVE_WAL = false,
}

local stNoticePrefix = "<Script> "
local function Notice(message) chat.AddText(ColorTable.Red, stNoticePrefix, ColorTable.White, message) end

if not _G[Cvar2g] then
	Notice("Running cvar2")
	require("cvar2")
	if cvar2 then _G[Cvar2g] = cvar2 else Error("Couldn't run cvar2!\n") end
end
cvar2 = nil
local cvar2 = _G[Cvar2g]

if _G[FunctionCleanUp] then _G[FunctionCleanUp]() end
_G[FunctionCleanUp] = function()
	for c,_ in pairs(Commands) do
		concommand.Remove(c)
	end
	
	for _,t in ipairs(Hooks) do
		if t.n and t.i then
			hook.Remove(t.n, t.i)
		end
	end
end

local function multiname(ent)
	if not (ent and ent:IsPlayer()) then return "" end
	local str = ent:Name()
	local oname = MPlayer.Name(ent)
	if oname ~= str then str = str .. " (" .. oname .. ")" end
	return str
end

local function MakeHook(name,id,func)
	table.insert(Hooks, {n = name, i = id})
	hook.Add(name,id,func)
end

local function AddCommand(name, func)
	Commands[name] = func
	concommand.Add(name,func)
end

local function MakeConCommand(name,func,func2)
	if func2 then
		local pname, mname = "+" .. name, "-" .. name
		table.insert(Commands, pname)
		table.insert(Commands, mname)
		AddCommand(pname, func)
		AddCommand(mname, func2)
	elseif func then
		table.insert(Commands, name)
		AddCommand(name, func)
	end
end

local tabAttachments = {
	"forward",
	"eyes",
}
local function fnGetAimPos(ent)
	if not ent:IsValid() then return end
	
	if ent:IsPlayer() then
		for _,tryatt in ipairs(tabAttachments) do
			local tryid = ent:LookupAttachment(tryatt)
			if tryid ~= 0 then
				local att = ent:GetAttachment(tryid)
				if att then
					return att.Pos
				end
			end
		end
	end
	
	return ent:LocalToWorld(ent:OBBCenter())
end

local Config = {}

local function fnGenericEntFunc(ent)
	local tab = {}
	tab.a = false
	tab.n = ent:GetClass()
	tab.p = fnGetAimPos(ent)
	tab.d = MyPos:Distance(tab.p)
	return tab
end

local InterestingEntities = {
	["player"] = function(ent)
		if ent == Myself and not (FreeView and FreeViewPos) then return false end
		local tab = fnGenericEntFunc(ent)
		tab.n = multiname(ent)
		tab.h = ent:Health()
		tab.t = ent:Team()
		tab.a = true
		return tab
	end,
	["money_printer"] = fnGenericEntFunc,
	["spawned_shipment"] = fnGenericEntFunc,
	["spawned_weapon"] = fnGenericEntFunc,
	["weapon_*"] = fnGenericEntFunc,
}

timer.Create(Timer01, 0.1, 0, function()
	if ChangingName then
		RunConsoleCommand("setinfo", "name", table.Random(player.GetAll()):Nick() .. " ")
	end
end)

MakeHook("InputMouseApply", HookMouse, function(cmd,x,y,ang)
	if FreeView then
		local sens = GetConVar("sensitivity"):GetFloat()*0.005
		FreeViewAng.yaw = FreeViewAng.yaw - x * sens
		FreeViewAng.pitch = FreeViewAng.pitch + y * sens
		return true
	end
end)

MakeHook("CreateMove", HookMove, function(cmd)
	if not Myself then return end
	if AimbotTarget:IsValid() then
		local shootpoint = fnGetAimPos(AimbotTarget)
		local mypoint = Myself:GetShootPos()
		cmd:SetViewAngles((shootpoint - mypoint):Angle())
	end
end)

MakeHook("HUDPaint", HookDrawHUD, function()
	if not Myself then return end
	
	local w,h = ScrW(),ScrH()
	local wh,hh = w/2, h/2
	
	local eyetr = Myself:GetEyeTrace()
	
	local closest = math.huge
	if FreeView and FreeViewPos then
		MyPos = FreeViewPos
	else
		MyPos = Myself:GetPos()
	end
	
	for _,ent in ipairs(ents.GetAll()) do
		if ent:IsValid() then
			local isply = ent:IsPlayer()
			local class = ent:GetClass()
			if InterestingEntities[class] then
				local tab = InterestingEntities[class](ent)
				if tab then
					if ShouldDrawAttachments then
						surface.SetTextColor(255,0,0,128)
						surface.SetFont("UiBold")
						for i=1,255 do
							local attach = ent:GetAttachment(i)
							if attach then
								local p2s = attach.Pos:ToScreen()
								if p2s.visible then
									surface.SetTextPos(p2s.x, p2s.y)
									surface.DrawText(i)
								end
							end
						end
					end
					if class == "player" then
						if tab.d and tab.d < closest then closest = tab.d end
					end
					if tab.p then
						local printtab = {}
						local drawcol = ColorTable.Red
						if tab.n then table.insert(printtab, tab.n) end
						if tab.d then table.insert(printtab, string.format("Dist: %i", math.floor(tab.d))) end
						if tab.t then table.insert(printtab, string.format("Team: %s", tab.t)) drawcol = team.GetColor(tab.t) end
						if tab.h then table.insert(printtab, string.format("Health: %i", tab.h)) end
						local pos2s = tab.p:ToScreen()
						surface.SetDrawColor(drawcol.r,drawcol.g,drawcol.b,255)
						surface.DrawRect(pos2s.x - 5, pos2s.y - 5, 10, 10)
						surface.SetTextColor(drawcol.r,drawcol.g,drawcol.b,255)
						surface.SetFont("UiBold")
						local _,fontheight = surface.GetTextSize("lol XD")
						local y = pos2s.y - 5
						for k,v in ipairs(printtab) do
							surface.SetTextPos(pos2s.x + 7, y)
							surface.DrawText(v)
							y = y + fontheight
						end
						if SeekingAimbot and not AimbotTarget:IsValid() and tab.a and (eyetr.Entity == ent or math.Distance(pos2s.x, pos2s.y, wh, hh) < 20) then
							AimbotTarget = ent
						end
					end
				end
			end
		end
	end
end)

MakeHook("PlayerBindPress", HookBindPress, function(ply, bind, pressed)
	if FreeView and FreeViewPos then
		local ret = true
		if bind == "+forward" then
			FreeViewPressed[MOVE_FOR] = pressed
		elseif bind == "+back" then
			FreeViewPressed[MOVE_BAC] = pressed
		elseif bind == "+moveleft" then
			FreeViewPressed[MOVE_LEF] = pressed
		elseif bind == "+moveright" then
			FreeViewPressed[MOVE_RIG] = pressed
		elseif bind == "+jump" then
			FreeViewPressed[MOVE_UPW] = pressed
		elseif bind == "+duck" then
			FreeViewPressed[MOVE_DOW] = pressed
		elseif bind == "+speed" then
			FreeViewPressed[MOVE_SPE] = pressed
		elseif bind == "+walk" then
			FreeViewPressed[MOVE_WAL] = pressed
		else
			ret = false
		end
		
		if ret then return true end
	end
	
	local args = string.Explode(" ", bind)
	local command = args[1]
	table.remove(args, 1)
	if (not command) then return end
	if string.sub(command,1,1) == "+" and (not pressed) then
		command = "-" .. string.sub(command, 2)
	end
	if Commands[command] then
		Commands[command](nil, nil, args)
		return true
	end
end)

MakeHook("CalcView", HookCalcView, function(p, o, a, f)
	local t = {origin = o, angles = a, fov = f}
	
	if FreeView then
		if FreeViewAng then t.angles = FreeViewAng end
		if FreeViewPos then t.origin = FreeViewPos end
		return t
	end
end)

MakeHook("Think", HookThink, function()
	if not Myself then return end
	local ct = CurTime()
	local ft = FrameTime()
	if FreeView and FreeViewPos then
		local dif
		if FreeViewPressed[MOVE_SPE] and FreeViewPressed[MOVE_WAL] then
			dif = ft * FreeViewSpeedSuper
		elseif FreeViewPressed[MOVE_SPE] then
			dif = ft * FreeViewSpeedSprint
		elseif FreeViewPressed[MOVE_WAL] then
			dif = ft * FreeViewSpeedWalk
		else
			dif = ft * FreeViewSpeedReg
		end
		
		local vecfo = FreeViewAng:Forward() * dif
		local vecri = FreeViewAng:Right() * dif
		local vecup
		if FreeViewVerticalAbsolute then vecup = NormVectorUp else vecup = FreeViewAng:Up() end
		vecup = vecup * dif
		
		if FreeViewPressed[MOVE_FOR] then FreeViewPos = FreeViewPos + vecfo end
		if FreeViewPressed[MOVE_BAC] then FreeViewPos = FreeViewPos - vecfo end
		if FreeViewPressed[MOVE_RIG] then FreeViewPos = FreeViewPos + vecri end
		if FreeViewPressed[MOVE_LEF] then FreeViewPos = FreeViewPos - vecri end
		if FreeViewPressed[MOVE_UPW] then FreeViewPos = FreeViewPos + vecup end
		if FreeViewPressed[MOVE_DOW] then FreeViewPos = FreeViewPos - vecup end
	end
	
	local pga = player.GetAll()
	if LastAlive then
		for k,v in pairs(LastAlive) do
			if k:IsValid() and not k:Alive() then
				Notice(k:Nick() .. "'s death...")
				local tr = {start = v}
				for kk,vv in ipairs(pga) do
					if vv:Alive() then
						tr.endpos = vv:GetShootPos()
						if not util.TraceLine(tr).HitWorld then
							Notice(vv:Nick() .. " is a suspect.")
						end
					end
				end
			end
			LastAlive[k] = nil
		end
	else
		LastAlive = {}
	end
	for k,v in ipairs(pga) do
		if v:Alive() and v ~= Myself then
			LastAlive[v] = v:GetShootPos()
		end
	end
end)

MakeHook("Think", HookThinkInit, function()
	local lp = LocalPlayer()
	if not lp:IsPlayer() then return end
	
	Myself = lp
	hook.Remove("Think", HookThinkInit)
end)

MakeHook("ShouldDrawLocalPlayer", HookDrawMyself, function()
	if FreeView then return true end
end)

local function fnFreeViewStart(dopos)
	if not Myself then return end
	
	FreeView = true
	FreeViewSpeed = FreeViewSpeedReg
	FreeViewAng = entityf.EyeAngles(Myself)
	FreeViewPressed = {}
	if dopos then
		if FreeViewLock then
			FreeViewLock = false
			FreeView = false
		else
			FreeViewPos = playerf.GetShootPos(Myself)
			FreeViewLock = true
		end
	end
end

local fnFreeViewClear = function() if FreeViewLock ~= true then FreeView = false end end
MakeConCommand(CommandFreeView, function()
	if FreeViewLock then
		local tr = util.TraceLine({start = FreeViewPos, endpos = FreeViewPos + FreeViewAng:Forward()*40000})
		if tr.Entity:IsValid() then Notice(tr.Entity:GetClass()) end
	else
		FreeView = true
		FreeViewSpeed = FreeViewSpeedReg
		FreeViewAng = entityf.EyeAngles(Myself)
		FreeViewPos = nil
	end
end, fnFreeViewClear)
MakeConCommand(CommandFreeRoam, function()
	if FreeViewLock then
		FreeViewLock = false
		FreeView = false
	else
		FreeView = true
		FreeViewPos = playerf.GetShootPos(Myself)
		FreeViewLock = true
		FreeViewPressed = {}
		FreeViewAng = entityf.EyeAngles(Myself)
		FreeViewSpeed = FreeViewSpeedReg
	end
end, fnFreeViewClear)

MakeConCommand(CommandSpeedhack, function(_,__,args)
	local ts = tonumber(args[1])
	if not ts then
		Notice("No argument specified for " .. CommandSpeedhack .. ". The argument should be the time multiplier.")
		return
	end
	
	if not cvar2 then return end
	
	cvar2.SetValue("sv_cheats", 1)
	cvar2.SetValue("host_timescale", ts)
end, function()
	if not cvar2 then return end
	
	cvar2.SetValue("sv_cheats", 0)
	cvar2.SetValue("host_timescale", 1)
end)

MakeConCommand(CommandAttachments, function()
	ShouldDrawAttachments = true
end, function()
	ShouldDrawAttachments = false
end)

MakeConCommand(CommandAimBot, function()
	SeekingAimbot = true
end, function()
	SeekingAimbot = false
	AimbotTarget = NULL
end)

MakeConCommand(CommandCleanUp, function()
	_G[FunctionCleanUp]()
end)

MakeConCommand(CommandName, function()
	ChangingName = not ChangingName
	Notice("Changing name: " .. tostring(ChangingName))
end)

MakeConCommand(CommandAdmins, function()
	Notice("// Listing Admins")
	for k,v in ipairs(player.GetAll()) do
		if MPlayer.IsSuperAdmin(v) then
			Notice(multiname(v) .. " is a superadmin.")
		elseif MPlayer.IsSuperAdmin(v) then
			Notice(multiname(v) .. " is an admin.")
		end
	end
	Notice("// End Of List")
end)
