// session_test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include "../../pkcs11_wrapper.h"

int _tmain(int argc, _TCHAR* argv[])
{
	if(argc < 2)
		return 1;

	char * p11_dll = argv[1];
	CK_TOKEN_INFO info = {0};

	pkcs11_wrapper p11_wrapper;

	if(0 != p11_wrapper.pkcs11_initialize(p11_dll))
	{
		return 1;
	}
	
	CK_FUNCTION_LIST_PTR pToken = p11_wrapper.GetFunctionsPtr();
	CK_RV rv = CKR_OK;

	CK_SLOT_ID_PTR pSlotList;
	CK_ULONG ulCount;
	CK_SESSION_HANDLE hSession;

	CK_INFO p11Info = {0};
	rv = pToken->C_GetInfo(&p11Info);
	ERROR_THROW(rv);

	rv = pToken->C_GetSlotList(CK_TRUE, NULL_PTR, &ulCount);
	ERROR_THROW(rv);

	pSlotList = (CK_SLOT_ID_PTR)new CK_SLOT_ID[ulCount];;
	rv = pToken->C_GetSlotList(CK_TRUE, pSlotList, &ulCount);
	ERROR_THROW(rv);
	
	rv = pToken->C_GetTokenInfo(pSlotList[0], &info);
	ERROR_THROW(rv);


	//Create a read only session
	rv = pToken->C_OpenSession(pSlotList[0], CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession);
	if (rv != CKR_OK)
	{
		delete[] pSlotList;
		return 2;
	}

	//Close all sessions
	rv = pToken->C_CloseAllSessions(pSlotList[0]);
	ERROR_THROW(rv);

	//Create a read write session
	rv = pToken->C_OpenSession(pSlotList[0], CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession);
	if (rv != CKR_OK)
	{
		delete[] pSlotList;
		return 2;
	}

	//so login
	CK_UTF8CHAR soPin[] = "00000000";
	rv = pToken->C_Login(hSession, CKU_SO, soPin, 8);
	ERROR_THROW(rv);

	//open a new session
	//rv = pToken->C_OpenSession(pSlotList[0], CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession);
	//ERROR_THROW(rv);
	
	//Close all sessions
	rv = pToken->C_CloseAllSessions(pSlotList[0]);
	ERROR_THROW(rv);

	CK_UTF8CHAR label[] = "k3label";
	rv = pToken->C_InitToken(pSlotList[0], soPin, 8, label);
	ERROR_THROW(rv);

	rv = pToken->C_OpenSession(pSlotList[0], CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession);
	ERROR_THROW(rv);
	
	rv = pToken->C_Login(hSession, CKU_SO, soPin, 8);
	ERROR_THROW(rv);

	CK_UTF8CHAR uPin[] = "11111111";
	rv = pToken->C_InitPIN(hSession, uPin, 8);
	ERROR_THROW(rv);

END_OF_FUN:

	if(rv != CKR_OK)
	{
		printf("Error = %0x \n", rv);
	}
	else
	{
		printf("Successfully!\n");
	}

	getchar();
	return 0;
}

