// LoginEXE.cpp : Defines the entry point for the application.
//

#include "tchar.h"

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <io.h>
#include <sys/stat.h>				//stat	함수

using namespace std;

//////////////////////////////////////////////////////////////////////////
#if defined _REGULAR_
	//////////////////////////////////////////////////////////////////////////
	//
	// 정섭
	#define STR_CLIENT_REGISTRY_SUBKEY (_T("Software\\ROW\\MP-Client"))
	#define STR_CLIENT_REGISTRY_VALUE_NAME	(_T("Folder"))
#elif defined _TEST_
	//////////////////////////////////////////////////////////////////////////
	//
	// 테스트섭
	#define STR_CLIENT_REGISTRY_SUBKEY (_T("Software\\ROW\\MP-Client"))
	#define STR_CLIENT_REGISTRY_VALUE_NAME (_T("TestFolder"))
#elif defined _BG_
	//////////////////////////////////////////////////////////////////////////
	//
	// 배틀그라운드 전용섭
	#define STR_CLIENT_REGISTRY_SUBKEY (_T("Software\\ROW\\MP-Client"))
	#define STR_CLIENT_REGISTRY_VALUE_NAME (_T("BGFolder"))
#endif


#define LOGINNEW	(_T("Login.new"))
#define LOGINFILE	(_T("Login.dat"))

#define LOGINRESNEW	(_T("LoginRes.new"))
#define LOGINRESFILE	(_T("LoginRes.dll"))

#define LC2NEW	(_T("lc2.new"))
#define LC2FILE	(_T("lc2.ogg"))
	

////////////////////////////////////////////////////////////////////////////////////
//

bool	IsFileExist( const char * filename )
{
	FILE * fp = fopen( filename, "r" );
	if( fp != NULL )
	{
		fclose( fp );
		return true;
	}
	return false;
}

const char* GetClientPathFromRegistry()
{
	HKEY hMPClientReg;
	DWORD dwReadType=0;
	DWORD dwReadLens=256;
	static char strPath[256];

	_tcscpy(strPath, "");

	if( RegOpenKeyEx( HKEY_LOCAL_MACHINE, _T(STR_CLIENT_REGISTRY_SUBKEY), 0, KEY_READ, &hMPClientReg ) == ERROR_SUCCESS )
	{
		RegQueryValueEx( hMPClientReg, STR_CLIENT_REGISTRY_VALUE_NAME, 0, &dwReadType, (unsigned char*)strPath, &dwReadLens );		
		RegCloseKey( hMPClientReg );
	}

	return strPath;
}


BOOL SetClientPathInRegistry( const char* szPath )
{
	HKEY hMPClientReg;
	
	if( RegOpenKeyEx( HKEY_LOCAL_MACHINE, _T(STR_CLIENT_REGISTRY_SUBKEY), 0, KEY_WRITE, &hMPClientReg ) == ERROR_SUCCESS )
	{
		LONG lResult = RegSetValueEx(hMPClientReg, STR_CLIENT_REGISTRY_VALUE_NAME, 0, REG_SZ, (LPBYTE)szPath, (unsigned long)strlen(szPath));
		if(ERROR_SUCCESS != lResult)
		{
			RegCloseKey( hMPClientReg );
			return FALSE;
		}

		RegCloseKey( hMPClientReg );
	}
	else
	{
		return FALSE;
	}
	
	return TRUE;
}


BOOL GetModulePath( char* szOut )
{
	TCHAR szTemp[MAX_PATH];
	GetModuleFileName( NULL, szTemp, MAX_PATH );
	
	TCHAR* pLastToken = NULL;
	pLastToken = strrchr( szTemp, '\\' );
	if( NULL == pLastToken )
	{
		pLastToken = strrchr( szTemp, '/' );
		if( NULL == pLastToken )
		{
			return FALSE;
		}
	}
	
	int nPathLen = pLastToken - szTemp;
	strncpy( szOut, szTemp, nPathLen );
	szOut[nPathLen] = '\0';

	return TRUE;
}


BOOL CreateReg(HKEY hReg)
{
	TCHAR strPath[MAX_PATH];

	GetModulePath( strPath );

	
	long lResult;
	lResult = RegSetValueEx(hReg, STR_CLIENT_REGISTRY_VALUE_NAME, 0, REG_SZ, (LPBYTE)strPath, (unsigned long)strlen(strPath));
	
	if(ERROR_SUCCESS != lResult)
	{
		wsprintf( strPath, "Error %d", lResult );
		MessageBox( NULL, strPath, "Error", MB_OK );
		return FALSE;
	}
	
	return TRUE;
}


int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
	// 국내 정/테섭, 배틀로한은 레지생성코드 없음
#if defined(_NATION_KR_) && ( defined(_REGULAR_) || defined(_TEST_) || defined(_BG_) )

	const char * pszClientPath = GetClientPathFromRegistry();
	
	if(!strcmp(pszClientPath, ""))
	{
		//		MessageBox( NULL, "클라이언트가 인스톨 되지 않았습니다. 다시 인스톨 해주세요.", "Risk Your Life", MB_OK );
		MessageBox( NULL, "Client is not installed. Please Install and try again.", "Risk Your Life", MB_OK );
	}

	// 국내 P2 정섭포함 해외 전 서버 - 레지스트리 미존재시 생성코드
#else
	
	// 레지스트리 미존재시 생성 코드
	char szTmp[300];
	HKEY hMPClientReg;
	long lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, STR_CLIENT_REGISTRY_SUBKEY, 0, KEY_READ, &hMPClientReg);
	
	if(ERROR_SUCCESS != lResult)
	{
		if(ERROR_FILE_NOT_FOUND == lResult)
		{
			unsigned long dwDisp = 0;
			lResult = RegCreateKeyEx(HKEY_LOCAL_MACHINE, STR_CLIENT_REGISTRY_SUBKEY, 0, NULL, REG_OPTION_NON_VOLATILE,
				KEY_ALL_ACCESS, NULL, &hMPClientReg, &dwDisp);
			if(ERROR_SUCCESS != lResult)
			{
				wsprintf( szTmp, "Error %d", lResult );
				MessageBox( NULL, szTmp, "Error", MB_OK );
				return FALSE;
			}
			
			if(FALSE == CreateReg(hMPClientReg))
			{
				RegCloseKey(hMPClientReg);
				return FALSE;
			}
		} else
		{
			wsprintf( szTmp, "Error %d", lResult );
			MessageBox( NULL, szTmp, "Error", MB_OK );
			return FALSE;
		}
	}
	RegCloseKey(hMPClientReg);
	
	char szModulePath[MAX_PATH];
	GetModulePath( szModulePath );

	const char * pszClientPath = GetClientPathFromRegistry();
	if( 0 != stricmp( pszClientPath, szModulePath ) )
	{
		SetClientPathInRegistry( szModulePath );
	}

	pszClientPath = GetClientPathFromRegistry();

#endif


	char strTmp[300];
	
	string LoginFile;
	LoginFile += pszClientPath;
	LoginFile += '\\';
	LoginFile += LOGINFILE;

	string LoginNew;
	LoginNew += pszClientPath;
	LoginNew += '\\';
	LoginNew += LOGINNEW;

	string LoginResFile;
	LoginResFile += pszClientPath;
	LoginResFile += '\\';
	LoginResFile += LOGINRESFILE;
	
	string LoginResNew;
	LoginResNew += pszClientPath;
	LoginResNew += '\\';
	LoginResNew += LOGINRESNEW;

	string LC2File;
	LC2File += pszClientPath;
	LC2File += '\\';
	LC2File += LC2FILE;
	
	string LC2New;
	LC2New += pszClientPath;
	LC2New += '\\';
	LC2New += LC2NEW;
	
	string strCmdLine = "Login";
	strCmdLine += " ";
	strCmdLine += lpCmdLine;


 	// TODO: Place code here.

	//////////////////////////////////////////////////////////////////////////
	if( IsFileExist( LoginNew.c_str() ) )
	{
		_chmod( LoginFile.c_str(), _S_IREAD | _S_IWRITE );
		remove( LoginFile.c_str() );
		if( rename( LoginNew.c_str(), LoginFile.c_str() ) != 0 )
			MessageBox( NULL, "Cannot Update Login.exe file", "Error!0x01", MB_OK );
	}

	if( !IsFileExist( LoginFile.c_str() ) )
	{
		MessageBox( NULL, "Login.dat file not found.", "Risk Your Life", MB_OK );
		return 0;
	}

	//////////////////////////////////////////////////////////////////////////
	if( IsFileExist( LoginResNew.c_str() ) )
	{
		_chmod( LoginResFile.c_str(), _S_IREAD | _S_IWRITE );
		remove( LoginResFile.c_str() );
		if( rename( LoginResNew.c_str(), LoginResFile.c_str() ) != 0 )
			MessageBox( NULL, "Cannot Update LoginRes.dll file", "Error!0x01", MB_OK );
	}

	if( !IsFileExist( LoginResFile.c_str() ) )
	{
		MessageBox( NULL, "LoginRes.dll file not found.", "Risk Your Life", MB_OK );
		return 0;
	}

	//////////////////////////////////////////////////////////////////////////
	if( IsFileExist( LC2New.c_str() ) )
	{
		_chmod( LC2File.c_str(), _S_IREAD | _S_IWRITE );
		remove( LC2File.c_str() );
		if( rename( LC2New.c_str(), LC2File.c_str() ) != 0 )
			MessageBox( NULL, "Cannot Update LC2.ogg file", "Error!0x01", MB_OK );
	}

	if( !IsFileExist( LC2File.c_str() ) )
	{
		MessageBox( NULL, "LC2.ogg file not found.", "Risk Your Life", MB_OK );
		return 0;
	}
	
	


	//이미 생성된 Login윈도우가 있으면 새로 실행하지 않고 종료함.
	HWND hWnd = FindWindow( "#32770", "Login" );
	if( hWnd != NULL )
	{
		SetForegroundWindow( hWnd );
		return 0;
	}

	hWnd = FindWindow( "#32770", "Update File Dialog" );
	if( hWnd != NULL )
	{
		SetForegroundWindow( hWnd );
		return 0;
	}
/*
	////////////////////////////////////////////////////////////////////////
	string gdFile;
	gdFile += pszClientPath;
	gdFile += '\\';
	gdFile += "ROWYouxi.mcf";

	string gdFileT;
	gdFileT += pszClientPath;
	gdFileT += '\\';
	gdFileT += "GameGuard\\Splash.jpg";

//	MessageBox(GetActiveWindow(), gdFile.c_str(), "ERROR", MB_OK);
//	MessageBox(GetActiveWindow(), gdFileT.c_str(), "ERROR", MB_OK);
//
	// 파일복사
	::CopyFile(gdFile.c_str(), gdFileT.c_str(), FALSE);
	////////////////////////////////////////////////////////////////////////
*/

    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

	if( !CreateProcess( LoginFile.c_str(), (char*)strCmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ) )
	{
//		MessageBox( NULL, "Login 프로그램을 실행할 수 없습니다.", "Risk Your Life", MB_OK );
//		MessageBox( NULL, "Cannot run [Login.dat] ", "Error!0x02", MB_OK );
		wsprintf( strTmp, "Cannot run [Login.dat] : Error code [%d]", GetLastError() );
		MessageBox( NULL, strTmp, "Error!0x02", MB_OK );
	}

	return 0;
}
