#pragma semicolon 1
#define PLUGIN_AUTHOR "jenz"
#define PLUGIN_VERSION "1.0"
#include <sourcemod>

public Plugin myinfo =
{
    name = "plugin_loader_unloader",
    author = PLUGIN_AUTHOR,
    description = "prevents slow map switches by loading and unloading plugins after map switching",
    version = PLUGIN_VERSION,
    url = "www.unloze.com"
};

public void OnMapStart()
{
    CreateTimer(10.0, init_plugins_global);
    CreateTimer(17.0, init_plugins_map);
}

public Action init_plugins_map(Handle hTimer)
{
    char sConfigFile[PLATFORM_MAX_PATH];
    BuildPath(Path_SM, sConfigFile, sizeof(sConfigFile), "configs/plugins_loading_unloading.cfg");
    if(!FileExists(sConfigFile))
    {
        LogMessage("Could not find config: \"%s\"", sConfigFile);
        return Plugin_Handled;
    }
    char map[PLATFORM_MAX_PATH];
    GetCurrentMap(map, PLATFORM_MAX_PATH);

    //for some reason keyvalues did not play along so just reading file instead.
    new Handle:fileHandle = OpenFile(sConfigFile, "r" );
    char lineBuffer[256];
    bool found_nextmap = false;
    while( !IsEndOfFile( fileHandle ) && ReadFileLine( fileHandle, lineBuffer, sizeof( lineBuffer ) ) )
    {
        TrimString( lineBuffer );
        ReplaceString(lineBuffer, sizeof(lineBuffer), "\"", "");
        if (StrEqual(lineBuffer, map))
        {
            found_nextmap = true;
        }
        if (StrContains(lineBuffer, "sm plugins") != -1 && found_nextmap)
        {
            ServerCommand(lineBuffer);
        }
        if (StrEqual(lineBuffer, "}") && found_nextmap)
        {
            break; //we found our specific next map and finished all plugins loading/unloading.
        }
    }
    CloseHandle( fileHandle );
    return Plugin_Handled;
}

public Action init_plugins_global(Handle hTimer)
{
    char sConfigFile[PLATFORM_MAX_PATH];
    BuildPath(Path_SM, sConfigFile, sizeof(sConfigFile), "configs/plugins_loading_unloading.cfg");
    if(!FileExists(sConfigFile))
    {
        LogMessage("Could not find config: \"%s\"", sConfigFile);
        return Plugin_Handled;
    }
    char map[PLATFORM_MAX_PATH];
    GetCurrentMap(map, PLATFORM_MAX_PATH);

    //for some reason keyvalues did not play along so just reading file instead.
    new Handle:fileHandle = OpenFile(sConfigFile, "r" );
    char lineBuffer[256];
    while( !IsEndOfFile( fileHandle ) && ReadFileLine( fileHandle, lineBuffer, sizeof( lineBuffer ) ) )
    {
        TrimString( lineBuffer );
        ReplaceString(lineBuffer, sizeof(lineBuffer), "\"", "");
        if (StrContains(lineBuffer, "sm plugins") != -1)
        {
            ServerCommand(lineBuffer);
        }
        if (StrEqual(lineBuffer, "}"))
        {
            break;
        }
    }
    CloseHandle( fileHandle );
    return Plugin_Handled;
}
