/*
   Copyright (C) 2007 Will Franklin.

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; either version 2
   of the License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

   See the GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

 */

#include "client.h"
#include "../qcommon/md5.h"
#include "../matchmaker/mm_hash.h"

int myuserid = 0;

//================
// AuthC_Auth
// Handle reply from authentication server
//================
static void AuthC_Auth( const socket_t *socket, const netadr_t *address )
{
	char *reply = Cmd_Argv( 1 );

#ifndef ENABLE_MATCHMAKER
	return;
#endif

	if( !strcmp( reply, "invalid" ) )
	{
		CL_UIModule_AuthReply( AUTH_INVALID );
		return;
	}

	if( !strcmp( reply, "valid" ) )
	{
		CL_UIModule_AuthReply( AUTH_VALID );
		myuserid = atoi( Cmd_Argv( 2 ) );
		return;
	}
}

//================
// Auth_Packets
// Authentication reply packets from master
//================
typedef struct
{
	char *name;
	void ( *func )( const socket_t *socket, const netadr_t *address );
} auth_cmds_t;

static auth_cmds_t auth_cmds[] =
{
	{ "auth", AuthC_Auth },
	{ NULL, NULL }
};

qboolean Auth_Packets( const socket_t *socket, const netadr_t *address, char *c )
{
	auth_cmds_t *cmd;

#ifndef ENABLE_MATCHMAKER
	return qfalse;
#endif

	if( !strcmp( NET_AddressToString( address ), cl_mmserver->string ) )
	{
		for( cmd = auth_cmds; cmd->name; cmd++ )
		{
			if( !strcmp( cmd->name, c ) )
			{
				cmd->func( socket, address );
				return qtrue;
			}
		}
	}

	return qfalse;
}


//================
// Auth_CheckUser
// Try to authenticate user. Either by previous authentication
// or by contacting auth server
//================
void Auth_CheckUser( const char *email, const char *pass )
{
	char pass2[HASH_SIZE];
	netadr_t address;

#ifndef ENABLE_MATCHMAKER
	return;
#endif

	if( myuserid )
	{
		CL_UIModule_AuthReply( AUTH_VALID );
		return;
	}

	if( !email || !pass )
	{
		CL_UIModule_AuthReply( AUTH_INVALID );
		return;
	}

	if( !NET_StringToAddress( cl_mmserver->string, &address ) )
	{
		CL_UIModule_AuthReply( AUTH_INVALID );
		return;
	}
	if( !address.port )
		address.port = BigShort( PORT_MASTER );

	MM_Hash( pass2, pass );
	Netchan_OutOfBandPrint( &cls.socket_udp, &address, "auth \"%s\" \"%s\"", email, pass2 );

	CL_UIModule_AuthReply( AUTH_CHECKING );
}
