/*
[]======================================================================[]

	Copyright(C) 1998-2003, Feitian Technologies Co., Ltd.
	All rights reserved.

FILE:
	ImportCert.cpp

DESC:
	Defines the entry point for the console application.

REVISION:
	2003-04-29 		
[]======================================================================[]
*/

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include "import.h"

typedef DWORD (*DLLImportCertFromFile)(IN char* certpath, IN char* password, IN char* UserPIN);

#define CERT_FILENAME TEXT("test.pfx")
#define CERT_PASSWORD TEXT("1234")
#define TOKEN_USERPIN TEXT("1234")

TCHAR* nck_FindPath(TCHAR* szPath, TCHAR* szFinded)
{
	if(NULL == szPath || NULL == szFinded)
	{
		return NULL;
	}

	lstrcpy(szFinded, szPath);

	int iLen = lstrlen(szFinded);
	int iPos = iLen;
	while(iPos > 0)
	{
		if(szFinded[iPos - 1] != TEXT('\\'))
			--iPos;
		else
		{
			szFinded[iPos] = TEXT('\0');
			break;
		}
	}

	return szFinded;
}

int main(int argc, char* argv[])
{
	TCHAR szTempPath[MAX_PATH] = {0};
	TCHAR szCertFileName[MAX_PATH] = {0};

	if(0 == GetModuleFileName(NULL, szTempPath, MAX_PATH))
	{
		printf("ERR: Can not get the current directory.\n");
		return(1);
	}

	if(NULL == nck_FindPath(szTempPath, szCertFileName))
	{
		printf("ERR: Can not get the certificate file name.\n");
		return(1);
	}
	lstrcat(szCertFileName, CERT_FILENAME);

	HINSTANCE hLib = LoadLibrary("ImportCertsDll.dll");
	if(NULL == hLib)
	{
		printf("\nLoadLibrary error!\n\nPress any key to exit...");
		getch();
		return 1;
	}

	DLLImportCertFromFile ImportCertFromFile = NULL;
	ImportCertFromFile = (DLLImportCertFromFile)GetProcAddress(hLib, "ImportCertFromP12File");
	if(NULL == ImportCertFromFile)
	{
		FreeLibrary(hLib);
		printf("\nCan not locate the Function.\n\nPress any key to exit...");
		getch();
		return 1;
	}

	printf("\nStart import certificate.\n");
	DWORD rv = ImportCertFromFile(szCertFileName, CERT_PASSWORD, TOKEN_USERPIN);
	if(0 == rv)
	{
		printf("All done, this librry works fine.\n");
	}
	else
	{
		printf("I got some error: rv = 0x%08X\n", rv);
	}
	FreeLibrary(hLib);
	printf("\nPress any key to exit...");
	getch();

	return 0;
}
 