#include <stdio.h>

#include "arg.h"
#include "common.h"
#include "crd_ut10xx.h"

int
main(int argc, const char **argv)
{
	const char *help = 
		"\n\tkey [-help] [-devnum=num] [-devname=name] [-gen=keyname]\n"
		"\t\t[-del] -keynum=num [-user] [-so] -pin=pin\n\n"
		"\t-help\n"
		"\t\tPrint this information.\n\n"
		"\t-devnum\n"
		"\t\tSpecifies number of device which should be initialised.\n"
		"\t\tNumbers of devices can be foun calling info program.\n"
		"\t\tDefault value of this number is equal 0 and correspond to\n"
		"\t\tthe first device attached to host.\n\n"
		"\t-devname\n"
		"\t\tDevice can be specified by 'name' (only if configured).\n"
		"\t\tIf user defines also -devnum, then this option is ignored.\n\n"
		"\t-gen\n"
		"\t\tThis option force device to generate key with specified\n"
		"\t\tname - 'keyname'.\n\n"
		"\t-del\n"
		"\t\tThis option permanently removes key from protected memory.\n\n"
		"\t-keynum\n"
		"\t\tSpecifies number of key on wich operation should be done.\n\n"
		"\t-user\n"
		"\t\tSpecifies, that PIN passed to programm belongs to User.\n\n"
		"\t-so\n"
		"\t\tSpecifies, that PIN passed to programm belongs to Security\n"
		"\t\tOfficer.\n\n"
		"\t-pin\n"
		"\t\tThis option specifies actual value of PIN.\n\n";
	
	CRD_UT10XX_t *ut;
	
	int devnum = -1;
	const char *devname = 0;
	const char *gen = 0;
	int del = 0;
	int keynum = 0;
	int user = 0;
	int so = 0;
	int pinid = -1;
	const char *pin = 0;
	
	int status = 0;
	
	if ( prologue(argv, help) )
		return (-1);
	
	if ( arg_getall(argv, "issb!ibb!s", "-devnum", &devnum, "-devname", 
		&devname, "-gen", &gen, "-del", &del, "-keynum", &keynum, "-user", 
		&user, "-so", &so, "-pin", &pin) < 0 )
		return (-2);
	
	if ((devname == 0) && (devnum < 0))
		devnum = 0;
	
	if (devnum >= 0)
	{
		if ( (ut = CRD_UT10XX_find_by_index(devnum)) == 0 )
		{
			epilogue(stderr, "there is no device of that number, use "
				"'info' to check\n", 0, 0);
			return (-3);
		}
	}
	else
	{
		if ( (ut = CRD_UT10XX_find_by_name(devname)) == 0 )
		{
			epilogue(stderr, "there is no device of this name, use "
				"'info' to check\n", 0, 0);
			return (-4);
		}
	}
	
	if (gen && del)
	{
		epilogue(stderr, "operations -gen and -gen exclude each other\n", 
			0, 0);
		return (-5);
	}
	
	if ((user && so) || (!user && !so))
	{
		epilogue(stderr, "exactly one PIN identifier must be specified\n", 
			0, 0);
		return (-6);
	}
	
	if (so) pinid = CRD_UT10XX_SO_PIN_ID;
	else pinid = CRD_UT10XX_USER_PIN_ID;
	
	CRD_UT10XX_session_open(ut);
	
	if (gen)
	{
		status = CRD_UT10XX_cmd_generate_key(ut, pin, pinid, gen, keynum);
	}
	else if (del)
	{
		status = CRD_UT10XX_cmd_delete_key(ut, pin, pinid, keynum);
	}
	
	CRD_UT10XX_session_close(ut);
	
	return (epilogue(stderr, 0, status, ut));
}
