#include <amxmodx>
#include <fakemeta>
#include <cstrike>

#define PLUGIN "Roundend Blocker"
#define VERSION "1.4"
#define AUTHOR "Jim"

#define BOT_NUM 2

new g_bot[BOT_NUM]
new g_botnum

new g_cvar_bot1
new g_cvar_bot2
new g_cvarMinToAddBots
new g_cvarMaxToKickBots
new g_maxplayers

public plugin_init() {
	register_plugin(PLUGIN, VERSION, AUTHOR)
	g_cvarMinToAddBots = register_cvar("rb_min_add","6")
	g_cvarMaxToKickBots = register_cvar("rb_max_kick","10")
	g_cvar_bot1 = register_cvar("rb_bot1_name", "Good Luck!")
	g_cvar_bot2 = register_cvar("rb_bot2_name", "Have Fun!")
	register_logevent("round_start", 2,"1=Round_Start")
	register_event("SendAudio", "round_end", "a", "2&%!MRAD_terwin", "2&%!MRAD_ctwin") 
	g_maxplayers = get_maxplayers()
}

public round_start() {
	if(g_botnum)
		hide_bot()
}

public round_end() {
	if(get_playersnum(1) < min(g_maxplayers - BOT_NUM, get_pcvar_num(g_cvarMinToAddBots))) {
		while(g_botnum < BOT_NUM)
			create_bot()
	}
}

public create_bot() {
	if(g_botnum == BOT_NUM) {
		server_print("[Roundend Blocker] You can't create any more.")
		return
	}
	new bot, botname[32]
	if(!g_botnum)	get_pcvar_string(g_cvar_bot1, botname, 31)
	else	get_pcvar_string(g_cvar_bot2, botname, 31)
	bot = engfunc(EngFunc_CreateFakeClient, botname)
	if(!bot) {
		server_print("[Roundend Blocker] Error!")
		return
	}
	new ptr[128]
	engfunc(EngFunc_FreeEntPrivateData, bot)
	dllfunc(DLLFunc_ClientConnect, bot, botname, "127.0.0.1", ptr)
	if(!is_user_connected(bot)) {
		server_print("[Roundend Blocker] Error: %s", ptr)
		return
	}
	g_bot[g_botnum++] = bot
	dllfunc(DLLFunc_ClientPutInServer, bot)
	set_pev(bot, pev_spawnflags, pev(bot, pev_spawnflags) | FL_FAKECLIENT)
	set_pev(bot, pev_flags, pev(bot, pev_flags) | FL_FAKECLIENT)
	cs_set_user_team(bot, g_botnum % 2 ? CS_TEAM_T : CS_TEAM_CT)
	server_print("[Roundend Blocker] ^"%s^" has been created.", botname)
}

public hide_bot() {
	new msgTeamInfo = get_user_msgid("TeamInfo")
	new bot
	for(new i; i < g_botnum; i++) {
		bot = g_bot[i]
		set_pev(bot, pev_effects, pev(bot, pev_effects) | EF_NODRAW)
		set_pev(bot, pev_solid, SOLID_NOT)
		set_pev(bot, pev_takedamage, DAMAGE_NO)
		engfunc(EngFunc_SetOrigin, bot, Float:{9999.0, 9999.0, 9999.0})
		message_begin(MSG_ALL, msgTeamInfo)
		write_byte(bot)
		write_string("SPECTATOR")
		message_end()
	}
}

public kick_bot() {
	if(!g_botnum) {
		server_print("[Roundend Blocker] There are no bots to kick.")
		return
	}
	server_cmd("kick #%d", get_user_userid(g_bot[--g_botnum]))
	server_print("[Roundend Blocker] A bot has been kicked.")
}

public client_putinserver(id) {
	if(g_botnum && get_playersnum() - g_botnum >= min(g_maxplayers - BOT_NUM, get_pcvar_num(g_cvarMaxToKickBots)))
		kick_bot()
}

public client_disconnect(id) {
	if(g_botnum < BOT_NUM && get_playersnum() - g_botnum <= get_pcvar_num(g_cvarMinToAddBots)) {
		create_bot()
		hide_bot()
	}
}

public plugin_end() {
	while(g_botnum)
		kick_bot()
}
