#include <stdio.h>

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

int
main(int argc, const char **argv)
{
	const char *help = 
		"\n\tadmin [-help] [-devnum=num] [-devname=name] [-erase] [-unlock]\n"
		"\t\t[-newpin=pin] -sopin=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-erase\n"
		"\t\tIf this option is present, then programm uses Security Officer\n"
		"\t\trights to erase device private memory. This option excludes\n"
		"\t\t-unlock and -newpin options.\n\n"
		"\t-unlock\n"
		"\t\tIf this option is present, then programm uses Security Officer\n"
		"\t\trights to unlock device. This option excludes -erase and\n"
		"\t\t-newpin options.\n\n"
		"\t-newpin\n"
		"\t\tThis option can be used to change Security Officer PIN. New PIN\n"
		"\t\tshould be specified as at most 8 character string. This option\n"
		"\t\texcludes -erase and -unlock options.\n\n"
		"\t-sopin\n"
		"\t\tThis option specifies actual value of Security Officer PIN.\n\n";
	
	CRD_UT10XX_t *ut;
	
	int devnum = -1;
	const char *devname = 0;
	int erase = 0;
	int unlock = 0;
	const char *newpin = 0;
	const char *sopin = 0;
	
	int status = 0;

	if ( prologue(argv, help) )
		return (-1);

	if ( arg_getall(argv, "isbbs!s", "-devnum", &devnum, "-devname", &devname, 
		"-erase", &erase, "-unlock", &unlock, "-newpin", &newpin, "-sopin",
		&sopin) < 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);
		}
	}
	
	CRD_UT10XX_session_open(ut);
	
	if ((erase != 0 && unlock != 0) || (erase != 0 && newpin != 0) 
		|| (unlock != 0 && newpin != 0))
	{
		CRD_UT10XX_session_close(ut);
		epilogue(stderr, "there are options which exclude each other\n", 0, 0);
		return (-5);
	}
	
	
	if (erase)
		status = CRD_UT10XX_cmd_dev_erase(ut, sopin);

	else if (unlock)
		status = CRD_UT10XX_cmd_dev_unlock(ut, sopin);

	else if (newpin)
		status = CRD_UT10XX_cmd_change_so_pin(ut, sopin, newpin);
	
	CRD_UT10XX_session_close(ut);
	
	return (epilogue(stderr, 0, status, ut));
}
