/* AMX Mod script.
*
* Command Aliasing
*  by JustinHoMi
*
* This script is intended to mimic clanmod-style aliasing (cm_alias)
*
* Usage: amx_alias "alias" "command" flags
*
*/

#include <amxmod>

#define MAX_ALIASES 64		// max num of aliases to load

new alias[MAX_ALIASES][32]
new cmd[MAX_ALIASES][32]
new cflags[MAX_ALIASES][5]	// cmd flags
new uflags[MAX_ALIASES]		// user flags
new anum = 0

// load and register the alias
public admin_alias(){
	read_argv(1,alias[anum],32)
	read_argv(2,cmd[anum],32)
	read_argv(3,cflags[anum],32)

	// seperate user flag and cmd flags
	new user_flags[2]
	format(user_flags,2,"%c",tolower(cflags[anum][0]))
	uflags[anum] = read_flags(user_flags)
	copy(user_flags,5,cflags[anum])

	// get the description of the original command
	new cflag,ccmd[32],cinfo[64],description[64]
	for(new i=0;i<get_clcmdsnum();i++)
	{
		get_clcmd(i,cflag,ccmd,32,cinfo,64)
		new length = strlen(cmd[anum])
		if (equal(cmd[anum],ccmd,length))
		{
			copy(description,64,cinfo)
			i=500 // break out of the loop
		}
	}

	// replace the name of the original cmd with the name of the alias in the desc
	new tmp[32]
	format(tmp,32,"%s ",alias[anum])
	replace(description,64,ccmd,tmp);

	// fix for when registered commands have no description
	if (contain(ccmd,description)!=-1)
		copy(description,32,alias[anum])

	// if it's a server-side cmd then it won't have a desc, so just show the cmd it aliases
	new	desc[32]
	if (description[0])
		format(desc,64,"%s",description)
	else
		format(desc,32,"%s (%s)",alias[anum],cmd[anum])

	// and we register the command with proper flags and description
	register_clcmd(alias[anum],"alias_run",uflags[anum],desc)
	server_print("[AMX] Alias ^"%s^" added",alias[anum])

	anum++

	return PLUGIN_CONTINUE
}

// run the alias
public alias_run(id){
	new thecmd[32]
	read_argv(0,thecmd,32)								// the name of the alias
	new args[64]
	read_args(args,64) 									// read the rest of the args

	for (new i=0; i<anum; i++)							// cycle through the stored aliases
	{
		if (equal(thecmd,alias[i])) 					// if called alias == stored alias
		{
			if (get_user_flags(id)&uflags[i])			// compare user flags
			{
				new command[64]
				format(command,64,"%s %s",cmd[i],args)	// put the new command and the args together
				if (contain(cflags[i],"l") != -1)		// client command
					client_cmd(id,command)
				else									// server command
					server_cmd("%s",command)
			}
			else client_print(id,print_console,"[AMX] You do not have access to this command")
		}
	}

	return PLUGIN_HANDLED
}

public plugin_init()
{
	register_plugin("Command Aliases","0.7","JustinHoMi")
	register_srvcmd("amx_alias","admin_alias")
	server_cmd("exec addons/amx/aliases.cfg")
	return PLUGIN_CONTINUE
}

