// init_token.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);

	CK_UTF8CHAR soPin[] = "00000000";
	CK_UTF8CHAR newsoPin[] = "00000000";

	if(info.flags & CKF_TOKEN_INITIALIZED)
	{
		rv = pToken->C_OpenSession(pSlotList[0],  CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL, NULL, &hSession);
		ERROR_THROW(rv);
		//so login
		rv = pToken->C_Login(hSession, CKU_SO, soPin, 8);
		ERROR_THROW(rv);

		rv = pToken->C_SetPIN(hSession, soPin, 8, newsoPin, 8);
		ERROR_THROW(rv);

		rv = pToken->C_Logout(hSession);
		ERROR_THROW(rv);

		rv = pToken->C_CloseAllSessions(pSlotList[0]);
		ERROR_THROW(rv);
	}

	rv = pToken->C_InitToken(pSlotList[0], newsoPin, 8, (CK_UTF8CHAR_PTR)"K3NEW");
	ERROR_THROW(rv);

	CK_UTF8CHAR_PTR wrongSOPin = (CK_UTF8CHAR_PTR)"wrongpin";
	rv = pToken->C_InitToken(pSlotList[0], wrongSOPin, 8, (CK_UTF8CHAR_PTR)"K3--");
	rv = (rv == CKR_OK);
	ERROR_THROW(rv);

	rv = pToken->C_InitToken(pSlotList[0], newsoPin, 8, (CK_UTF8CHAR_PTR)"K3NEW");
	ERROR_THROW(rv);

	rv = pToken->C_OpenSession(pSlotList[0],  CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL, NULL, &hSession);
	ERROR_THROW(rv);

	rv = pToken->C_Login(hSession, CKU_SO, newsoPin, 8);
	ERROR_THROW(rv);

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


	rv = pToken->C_Finalize(NULL);
END_OF_FUN:

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

	getchar();
	return 0;
}

