#include <stdio.h>
#include <string.h>

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

int
main(int argc, const char **argv)
{
	const char *help = 
		"\n\tconf [-help] [-devnum=num] [-upcna] -devname=name -sopin=pin\n"
		"\t\t-sopinlim=num -upin=pin -upinlim=num\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-upcna\n"
		"\t\tIf this option is present, then device is configured with User\n"
		"\t\tPIN change not allowed bit. This means, that Security Officer\n"
		"\t\tcan't change User PIN.\n\n"
		"\t-devname\n"
		"\t\tSpecifies 'name' of configured device. This string should\n"
		"\t\thave at most 10 characters. If there is more than 10 characters,\n"
		"\t\tthen rest will be ignored.\n\n"
		"\t-sopin\n"
		"\t\tSpecifies string of at most 8 characters, that will be\n"
		"\t\tSecurity Officer PIN. If there is more than 8 characters, than\n"
		"\t\trest will be ignored.\n\n"
		"\t-sopinlim\n"
		"\t\tSpecifies limit of trys to give correct SO PIN. This number\n" 
		"\t\tshould be less or equal 255. If not it will be reduced modulo\n"
		"\t\t256.\n\n"
		"\t-upin\n"
		"\t\tSpecifies string of at most 8 characters, that will be\n"
		"\t\tUser PIN. If there is more than 8 characters, than rest will\n"
		"\t\tbe ignored.\n\n"
		"\t-upinlim\n"
		"\t\tSpecifies limit of trys to give correct SO PIN. This number\n"
		"\t\tshould be less or equal 255. If not it will be reduced modulo\n"
		"\t\t256.\n\n";
	
	CRD_UT10XX_t *ut;
	
	int devnum = 0;
	int upcna = 1;
	const char *name = 0;
	const char *sopin = 0;
	int sopinlim = 0;
	const char *upin = 0;
	int upinlim = 0;
	int status;
	
	if ( prologue(argv, help) )
		return (-1);
	
	if ( arg_getall(argv, "ib!s!s!i!s!i", "-devnum", &devnum, "-upcna", &upcna, 
		"-devname", &name, "-sopin", &sopin, "-sopinlim", &sopinlim, "-upin", 
		&upin, "-upinlim", &upinlim) < 0 )
		return (-2);
	
	if ( (ut = CRD_UT10XX_find_by_index(devnum)) == 0 )
	{
		epilogue(stderr, "there is no device of this number, use 'info'"
			" to check\n", 0, 0);
		return (-3);
	}
	
	ut->conf.info = upcna << 4;
	strncpy(ut->conf.name, name, 11);
	ut->conf.so_pin_limit = sopinlim;
	ut->conf.user_pin_limit = upinlim;
	strncpy(ut->conf.so_pin, sopin, 8);
	strncpy(ut->conf.user_pin, upin, 8);
	
	CRD_UT10XX_session_open(ut);
	status = CRD_UT10XX_cmd_dev_conf(ut);
	CRD_UT10XX_session_close(ut);
	
	return (epilogue(stderr, 0, status, ut));
}
