/*
 * snkkey - generate SNK card keys
 *
 * Part of the SNK extension to logdaemon
 *
 * Written by William LeFebvre, Argonne National Laboratory
 */

#include <stdio.h>
#include <stdlib.h>
#include "snk.h"

char *getline(buf, sz)

char *buf;
int sz;

{
    register char *r;

    if ((r = fgets(buf, sz, stdin)) != NULL)
    {
	buf[strlen(buf)-1] = '\0';
    }
    return(r);
}

main(argc, argv)

int argc;
char *argv[];

{
    unsigned char key[8];
    static unsigned char data[8];   /* initialized to 0 */
    char line[256];
    register int i;
    register int cnt = 1;
    int serials = 0;

    if (argc > 1)
    {
	if (argv[1][0] == '-')
	{
	    switch(argv[1][1])
	    {
	      case '\0':      /* input contains serial numbers */
		serials = 1;
		cnt = 0;
		break;

	      default:
		fprintf(stderr, "Usage: snkkey [ - ] [ cnt ]\n");
		exit(1);
		break;
	    }
	}
	else
	{
	    cnt = atoi(argv[1]);
	}
    }

    while ((serials && getline(line, sizeof(line)) != NULL) || cnt-- > 0)
    {
	i = 0;
	while (i < 8)
	{
	    key[i++] = randomnumber(1);
	}

#ifdef DEBUG
	for (i = 0; i < 8; i++)
	{
	    printf("%03o ", key[i]);
	}
	printf("\n");
#endif

	data[0] = data[1] = data[2] = data[3] = 
	data[4] = data[5] = data[6] = data[7] = '\0';

	snk_encrypt(data, key);

	printf("%s:", line);
	i = 0;

	/* this do...while with the funny while clause is done this way
	   to insure that a space gets put out after every octal value
	   EXCEPT the last one! */
	do
	{
	    printf("%03o", key[i++]);
	}
	while (i < 8 && (putchar(' ') != EOF));

	printf(":%02x%02x%02x\n", data[0], data[1], data[2]);
    }
    exit(0);
}
