/*
* Auth Check: Utilizes mysql to ensure only authorized steam ids run the game
* @author: Joseph 'Pcjoe' Florencio
* @date: 6/22/06
*/

#include "auth_check.h"
CAuthCheck g_AuthCheck;
extern char g_ipList[33][32];
#ifdef _WIN32
#include <winsock.h>
#endif

void getREALIP( char *pszIPAddress )
{	
	#ifdef _WIN32

	// We don't have a fake loopback address, it's a-okay
	if (strcmp(pszIPAddress, "loopback") != 0)
	{	return;
	}

	// Get 'real' ip address
	WSAData wsaData;
	if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
		return;

	char ac[80];
	if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR)
		return;

	struct hostent *phe = gethostbyname(ac);
	if (phe == 0)
		return;

	for (int i = 0; phe->h_addr_list[i] != 0; ++i)
	{	struct in_addr addr;
		memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));

		strcpy(pszIPAddress,inet_ntoa(addr));
		break;
	}

	WSACleanup();
	#endif
}

// Global func: is Authorized
int isAuthorizedUser(const char *pszSteamID, int iIndex )
{
	#ifdef _WIN32	
	// Check for auth
	if(!g_AuthCheck.Connect())
	{	return 0;
	}
	else
	{	// Get real IP address if we don't have one already
		getREALIP(g_ipList[iIndex]);
		// Log IP/steam ID information
		g_AuthCheck.addLog( pszSteamID, g_ipList[iIndex] );
		// Boot if we're not authorized to play
		if(!g_AuthCheck.isAuthorized( pszSteamID ))
		{	g_AuthCheck.closeConnection();
			return 0;
		}
		g_AuthCheck.closeConnection();
	}
	#endif
	return 1;
}



// Connect
bool CAuthCheck::Connect()
{	
	#ifdef _WIN32
	// Connect to server
	if(mysql_real_connect(&m_con, "skinner3d.com", "skinner_esfauth", "d0nth4x0rz512","skinner_esforcesauth",3306,NULL,0))
		return true;
	return false;
	#endif
    return true;	
}

// Close Connection
void CAuthCheck::closeConnection()
{	
	#ifdef _WIN32
	mysql_close(&m_con);
	#endif
}

// Add Log
void CAuthCheck::addLog( const char *steamID, const char *ipAddress )
{	
	#ifdef _WIN32
	char szQuery[512];
	// Create query
	sprintf(szQuery,"INSERT INTO logged (steamid, ip) VALUES ('%s', '%s')",steamID, ipAddress);
	// Execute query
	mysql_real_query(&m_con, szQuery, strlen(szQuery));
	#endif
}

// Is Authorized
bool CAuthCheck::isAuthorized( const char *steamID )
{
	#ifdef _WIN32
	char szQuery[512];
	// Create query
	sprintf(szQuery, "SELECT * FROM valid_users WHERE steamid='%s' LIMIT 1", steamID);
	// Execute query
	mysql_real_query(&m_con, szQuery, strlen(szQuery));
	// Store query	
	MYSQL_RES *res = mysql_store_result(&m_con);

	// Found entry
	if(mysql_fetch_row(res))
		return true;
	
	//HACK by harSens, no auth check
	//return true;

	return false;
	#endif
	return true;
}
