view utils/sws-email2db.c @ 24:47a491a16de3

utils/Makefile: use ${LIBUTIL} instead of ${LIBS}
author Mychaela Falconia <falcon@freecalypso.org>
date Mon, 15 Mar 2021 08:43:08 +0000
parents 372ecc4aa2c4
children
line wrap: on
line source

/*
 * This program reads extracts from Sysmocom webshop emails containing
 * card provisioning data and converts these bits into our sws-card-db
 * format.
 */

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

#define	MAX_FIELDS	32
#define	MAX_FIELD_KW	7

char *infname;
FILE *inf;
char linebuf[128];
int lineno;

char field_names[MAX_FIELDS][MAX_FIELD_KW+1];
unsigned nfields;

get_input_line()
{
	char *cp;

	if (!fgets(linebuf, sizeof linebuf, inf))
		return(0);
	lineno++;
	cp = index(linebuf, '\n');
	if (!cp) {
		fprintf(stderr, "%s line %d: too long or missing newline\n",
			infname, lineno);
		exit(1);
	}
	*cp = '\0';
	return(1);
}

read_field_names()
{
	for (;;) {
		if (!get_input_line()) {
			fprintf(stderr, "error: %s EOFs in field name list\n",
				infname);
			exit(1);
		}
		if (!linebuf[0])
			break;
		if (nfields >= MAX_FIELDS) {
			fprintf(stderr, "%s line %d: too many fields\n",
				infname, lineno);
			exit(1);
		}
		if (strlen(linebuf) > MAX_FIELD_KW) {
			fprintf(stderr, "%s line %d: field name is too long\n",
				infname, lineno);
			exit(1);
		}
		strcpy(field_names[nfields], linebuf);
		nfields++;
	}
	if (!nfields) {
		fprintf(stderr, "error: %s header defines 0 fields\n", infname);
		exit(1);
	}
}

process_one_card()
{
	unsigned nf;
	int rc;

	for (nf = 0; nf < nfields; nf++) {
		for (;;) {
			rc = get_input_line();
			if (!rc) {
				if (!nf)
					exit(0);
				fprintf(stderr,
			"error: %s EOFs in the middle of a card data block\n",
					infname);
				exit(1);
			}
			if (linebuf[0])
				break;
			if (nf) {
				fprintf(stderr,
		"%s line %d: empty line in the middle of a card data block\n",
					infname, lineno);
				exit(1);
			}
		}
		if (nf)
			putchar(' ');
		printf("%s=%s", field_names[nf], linebuf);
	}
	putchar('\n');
}

main(argc, argv)
	char **argv;
{
	if (argc != 2) {
		fprintf(stderr, "usage: %s email-extract-file\n", argv[0]);
		exit(1);
	}
	infname = argv[1];
	inf = fopen(infname, "r");
	if (!inf) {
		perror(infname);
		exit(1);
	}
	read_field_names();
	for (;;)
		process_one_card();
}