require("roc")

if !file.IsDir("pax", "DATA") then
	file.CreateDir("pax")
end

if !file.IsDir("pax/steals", "DATA") then
	file.CreateDir("pax/steals")
end

if !file.IsDir("pax/steals", "DATA") then
	file.CreateDir("pax/steals")
end

local autorun = nil

local function PaXLog(msg)
	MsgC(Color(16, 53, 235), "PaX>> ", Color(255, 255, 255), msg .. "\n")
end

PaXLog("Loaded!")

concommand.Add("pax_run_auto", function(ply, cmd, args, argStr)
	autorun = argStr
	PaXLog("File lua/" .. argStr .. " will load on autorun! Make sure to use backups of everything!")
end )

concommand.Add("pax_run_client", function(ply, cmd, args, argStr)
	RunOnClient(argStr, "lua/includes/util/color.lua")
end )

concommand.Add("pax_openscript", function(ply, cmd, args, argStr)
	RunOnClient(file.Read("lua/" .. args[1], "GAME"), args[2] or "lua/includes/util/color.lua")
end )

concommand.Add("pax_run_menu", function(ply, cmd, args, argStr)
	RunStringEx(argStr, "PaXMenu")
end )

local hostname = "ERROR_FAILED_TO_GET_HOSTNAME"
local append = {
	Startup = true,
	RunString = true,
	LuaCmd = true,
}

local badname = {
	"\\",
	"/",
	":",
	"*",
	"?",
	'"',
	"<",
	">",
	"|",
}

local oGameDetails = GameDetails

function GameDetails(sn, su, mn, mp, sid, gm)
	local safehn = sn

	for k,v in next, badname do
		local new = safehn:gsub(v, "")
		safehn = new
	end

	hostname = string.lower(safehn)
	oGameDetails(sn, su, mn, mp, sid, gm)
end

local function DumpFile(name, source)
	if name == "gamemode/base/cl_init.lua" then return end

	if !file.IsDir("pax/steals/" .. hostname, "DATA") then
		file.CreateDir("pax/steals/" .. hostname)
		PaXLog("Created filestealer directory! (pax/steals/" .. hostname .. ")")
	end

	if !append[name] then
		//PaXLog("Ran & stole file " .. name .. ", dumped to pax/steals/" .. hostname .. "/" .. name .. ".txt")
		
		local garbage = {}

		for i = 1, #name do
			if name[i] == "/" then
				garbage[#garbage + 1] = i
			end 		
		end

		if #garbage > 1 then
			local str = name
		
			for i = 1, #garbage do
				file.CreateDir("pax/steals/" .. hostname .. "/" .. string.sub(str, 1, garbage[i] - 1))
			end

			file.Write("pax/steals/" .. hostname .. "/" .. name .. ".txt", source)
		else
			file.Write("pax/steals/" .. hostname .. "/" .. name .. ".txt", source)
		end
	else
		file.Append("pax/steals/" .. hostname .. "/" .. name .. ".txt", "\n\n\n " .. source)
	end
end

hook.Add("RunOnClient", "PaX", function(name, source)
	if name == "lua/includes/init.lua" then
		RunOnClient(source, name)

		if autorun != nil and file.Exists("lua/" .. autorun, "GAME") then
			RunOnClient(file.Read("lua/" .. autorun, "GAME"), "lua/includes/util.lua")
			PaXLog("B4Autorun file loaded!")
		end

		return "local 2slow = nil"
	else
		DumpFile(name, source)
		return file.Read("pax/overrides/" .. name, "DATA") or source
	end
end)