/*
 * ==================================================================
 * Module:			joindeop
 * Author:			w00t <surreal.w00t@gmail.com>
 * Version:			1.0.0
 * Written For:		Stealth (and others).
 * Licence:			GPL
 * Description:		Deops a user on join to a new channel if user
 *				is not an oper.
 * ==================================================================
 */


 /* ChangeLog:
 *	28/09/2005 - 1.0.0
 *		-Initial version
 */

#include "config.h"
#include "struct.h"
#include "common.h"
#include "sys.h"
#include "numeric.h"
#include "msg.h"
#include "channel.h"
#include <time.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <io.h>
#endif
#include <fcntl.h>
#include "h.h"
#ifdef STRIPBADWORDS
#include "badwords.h"
#endif
#ifdef _WIN32
#include "version.h"
#endif

static int			cb_join(aClient *, aClient *, aChannel *, char *[]);


Hook *joindeop_hookjoin;

ModuleHeader MOD_HEADER(jointhrottle)
  = {
	"joindeop",
	"v1.0.0",
	"Deops non-opers on joining a new channel by w00t <surreal.w00t@gmail.com>",
	"3.2-b8-1",
	NULL 
    };

DLLFUNC int MOD_INIT(jointhrottle)(ModuleInfo *modinfo)
{
	joindeop_hookjoin = HookAddEx(modinfo->handle, HOOKTYPE_LOCAL_JOIN, cb_join);

	return MOD_SUCCESS;
}

DLLFUNC int MOD_LOAD(jointhrottle)(int module_load)
{
	return MOD_SUCCESS;
}

DLLFUNC int MOD_UNLOAD(jointhrottle)(int module_unload)
{
	if (joindeop_hookjoin)
		HookDel(joindeop_hookjoin);
		
	joindeop_hookjoin = NULL;
	
	return MOD_SUCCESS;
}

static int cb_join(aClient *cptr, aClient *sptr, aChannel *chptr, char *parv[])
{
	Member *cm;
	
	if (!IsOper(sptr))
	{
		//sendto_realops("%s is joining %s and not an oper", sptr->name, chptr->chname);
		
		/* appropriated from m_svsmode.c, why do_cmd didn't like me I have nfi.. */
		for (cm = chptr->members; cm; cm = cm->next)
		{
			//sendto_realops("Comparing %s to %s", cm->cptr->name, sptr->name);
			if (cm->cptr->name == sptr->name)
			{
				//sendto_realops("Match found.");
				if (cm->flags & CHFL_CHANOP)
				{
					Membership *mb;
					
					//sendto_realops("Match is opped, deopping.");
					mb = find_membership_link(cm->cptr->user->channel,
						chptr);				
					
					sendto_channel_butserv(chptr, (aClient *)find_server_quick_search(me.name), ":%s MODE %s %s %s",
						me.name, chptr->chname, "-o", cm->cptr->name);
					sendto_serv_butone(NULL, ":%s MODE %s %s %s", me.name, chptr->chname, "-o", cm->cptr->name);
					cm->flags &= ~CHFL_CHANOP;
					if (mb)
						mb->flags = cm->flags;
				}
			}
		}
	}
	return HOOK_CONTINUE;
}
