/* AMX Mod script.
*
* (c) Copyright 2002, Noplay
* This file is provided as is (no warranties).
*
*/

/*
With this plugin you load a cfg different by server id

for example if you server id are 1, the plugin load:
addons/amx/server/1.cfg

At each launch of the server the file are load from mysql

But your (listen)server.cfg are launch before

*/

/*

This AMX plugin requires MySQL MetaSmall module.

For this to work, you might create your MySQL table with this SQL query :

CREATE TABLE srvid_files (
  srv tinyint(5) NOT NULL default '0',
  content mediumtext NOT NULL,
  UNIQUE KEY srv (srv),
) TYPE=MyISAM;


Notes :
. check $moddir/addons/amx/mysql.cfg for MySQL access configuration

*/

#include <amxmod>
#include <mysql>

public load_files()
{
	new mysql
	new file[65]
	new content[3025]
	new error[257]
	new host[65]
	new user[33]
	new pass[33]
	new db[33]
	new srv_id[5]
	new query[256]
	new defaut[256]
	
	get_cvar_string("amx_mysql_host",host,64)
	get_cvar_string("amx_mysql_user",user,32)
	get_cvar_string("amx_mysql_pass",pass,32)
	get_cvar_string("amx_mysql_db",db,32)

	get_cvar_string("amx_server_id",srv_id,4) 


	mysql = mysql_connect(host,user,pass,db,error,256)
	if(mysql>0)
	{
		format(query,255,"SELECT content FROM srvid_files WHERE `srv`=('%s')",srv_id) 

		if(mysql_query(mysql,query)>0)
		{
			format(file,64,"addons/amx/server/%s.cfg",srv_id) 

			mysql_nextrow(mysql)
			mysql_getfield(mysql,1,content,3024)
				
			delete_file(file)
			
			format(defaut,255,"say [PHPAMX] Server %s configuration file loaded ",srv_id) 

			
			write_file(file,defaut,-1)
			write_file(file,content,-1)
		}
		else
		{
			mysql_error(mysql,error,32)
			server_print("MySQL error : could not load file : '%s'",error)
		}
		mysql_close(mysql)
	}
	else
	{
		server_print("MySQL error : could not connect : '%s'",error)
	}
	
	format(file,30,"addons/amx/server/%s.cfg",srv_id) 

	if(file_exists(file)==1)
	{
		server_cmd("exec %s",file)
	}

	
	return PLUGIN_HANDLED
}

public plugin_init()
{
	register_plugin("Server id file from MySQL","0.1","Noplay")
	register_cvar("amx_mysql_host","127.0.0.1")
	register_cvar("amx_mysql_user","root")
	register_cvar("amx_mysql_pass","")
	register_cvar("amx_mysql_db","amx")
	register_cvar("amx_server_id","0")

	set_task(0.1,"load_files")
	return PLUGIN_CONTINUE
}