#include <regex>

static const String:g_sLogPath[] = "addons/sourcemod/logs/admin_password_checker.log";
new String:sInfoVar[32];

public Plugin:myinfo = 
{
	name = "Admin Password Checker", 
	author = "Danyas",
	version = "1.2"
}

public OnPluginStart()
{
	if (!GetPassInfoVar(sInfoVar, sizeof(sInfoVar)))
	{
		SetFailState("PassInfoVar не найден в файле core.cfg");
	}
//	else	LogMessage("Переменная PassInfoVar имеет значение '%s'",sInfoVar);
}

public OnClientAuthorized(client, const String:sAuth[])
// STEAM_ID_PENDING? -> OnClientPutInServer (DarkSlide)	
// but i think OnClientPreAdminCheck better than OnClientPutInServer (Danyas)
{
	if (client > 0)
	{
		new Handle:hDataPack = CreateDataPack();
		WritePackString(hDataPack, sAuth);
		QueryClientConVar(client, sInfoVar, OnQueryClientConVar, hDataPack);
	}
}

public OnQueryClientConVar(QueryCookie:hCookie, client, ConVarQueryResult:hResult, const String:sConVarName[], const String:sConVarValue[], any:hDataPack)
{
	ResetPack(hDataPack);
	decl String:sAuth[64];
	ReadPackString(hDataPack, sAuth, sizeof(sAuth));
	sAuth[6] = '0';
	new AdminId:admin = FindAdminByIdentity(AUTHMETHOD_STEAM, sAuth);
	if (admin != INVALID_ADMIN_ID)
	{
		decl String:sPassword[64];
		if (GetAdminPassword(admin, sPassword, sizeof(sPassword)))
		{
			//PrintToServer("Acesss: sPassword = %s : CVAR = %s 'setinfo %s ПАРОЛЬ'", sPassword, sConVarValue, sInfoVar);
			if (!sConVarValue[0])
			{
				KickClient(client, "Введите пароль в консоле. 'setinfo %s ПАРОЛЬ'", sInfoVar);
				LogToFileEx(g_sLogPath, "%L Пытался зайти без пароля.", client);
			}
			else if (!StrEqual(sPassword, sConVarValue)) 
			{
				KickClient(client, "Вы ввели неверный пароль! 'setinfo %s ПАРОЛЬ'", sInfoVar);
				LogToFileEx(g_sLogPath, "%L Пытался зайти с паролем %s", client, sConVarValue);
			}
		}
		//else PrintToServer("Админ без пароля");
	}
	//else PrintToServer("INVALID_ADMIN_ID");
	CloseHandle(hDataPack);
}

bool:GetPassInfoVar(String:value[], maxlength)
{
	new Handle:file = OpenFile("addons/sourcemod/configs/core.cfg", "rt");
	if (file != INVALID_HANDLE)
	{
		new Handle:re = CompileRegex("^\\s+\"PassInfoVar\"\\s+\"(\\w+)\""); // ([^\"]*)
		if (re != INVALID_HANDLE)
		{
			decl String:buffer[PLATFORM_MAX_PATH];
			while (!IsEndOfFile(file) && ReadFileLine(file, buffer, sizeof(buffer)))
			{
				if (MatchRegex(re, buffer) > 0 && GetRegexSubString(re, 1, value, maxlength))
				{
					CloseHandle(re);
					CloseHandle(file);
					return true;
				}
			}
			CloseHandle(re);
		}
		CloseHandle(file);
	}
	return false;
}