/* load a file of text into a db data base for use with the version server */
#include <ndbm.h>
#include <stdio.h>
#include <errno.h>
#include <netdb.h>
#include <ctype.h>
#include <fcntl.h>
#include "v.h"


#define LINE_SIZE 1024

int line_num = 0;				/* Global!  So THERE. */

/*
 * Return pointer to start of next field (after it's starting colon) 
 */

static char *next_field(char **ptr)
	{
	register char  *cp = *ptr;
	
	cp = (char *) strchr(cp, DLM);
	if (cp) 
		{
		*cp++ = '\0';
		while (*cp && isspace(*cp)) ++cp;
		return *ptr = cp;
		}
	else
		{
		fprintf(stderr,"Line %d too short\n", line_num);
		return *ptr;
		}
	}

static void usage()
	{
	fprintf(stderr,"usage: load_db [-v]\n");
	exit(1);
	}
	
main(argc, argv)
     int argc;
     char **argv;
	{
	DBM *db;
	FILE *ver_file;
	datum rec,key;
	char line[LINE_SIZE], stat[2];
	char thekey[KEY_SIZE],*cp,*name,*version,*msg,*status,*platform;
	struct v_info v_info;
	struct v_pkt v_pkt;
	int rc, verbose=0;
	int vs;
	
	while (++argv, --argc) 
		{
		if (!strcmp(*argv, "-v")) 
			++verbose;
		else
			usage();
		}
	if (!(ver_file = fopen(VERSION_FILE,"r"))) 
		{ /* text file */
		perror(VERSION_FILE);
		exit(1);
		}
	
	db = dbm_open(VERSION_DB_FILE, O_CREAT | O_RDWR ,(int) 0644);
	if (!db) 
		{
		printf("couldn't open db\n");
		perror("db open");
		exit(1);
		}
	
	while (fgets(line,1024, ver_file)) 
		{
		++line_num;
		if (cp = (char *) strchr(line, '#'))
			*cp = 0;
		if (cp = (char *) strrchr(line, '\n')) 
			*cp = 0;
		cp = line;
		while (*cp && isspace(*cp)) cp++;
		if (*cp) 
			{
			name = cp;
			version = next_field(&cp);
			platform = next_field(&cp);
			status = next_field(&cp);
			msg = next_field(&cp);
			
			for (vs = 0;
			     version_status[vs].status != V_BAD_STATUS &&
			     strcmp(version_status[vs].status_name, status);
			     vs++);
			if ((stat[0] = version_status[vs].status) == V_BAD_STATUS) 
				{ 
				fprintf(stderr, "Line %d: Bad status: %s\n", line_num, status);
				exit(1);
				}
			stat[1] = 0;
					/* First, put a record of this application in the db */
			key.dptr = name;
			key.dsize = strlen(key.dptr) + 1;
			rec.dptr = name;
			rec.dsize = 0;
			dbm_store (db, key, rec, DBM_INSERT);
			
					/* Now record this specific version */
			sprintf(thekey,"%s%s%s",name,version,platform);
			
			if (verbose) 
				printf("name = %s, version = %s, platform = %s, status = %d,msg = %s,key = %s\n",
				       name,version,platform,vs,msg,thekey);
			
			key.dptr = thekey;
			key.dsize = strlen(key.dptr) + 1;
			
			memset(&v_info, 0, sizeof(v_info));
			v_info.status = stat;
			v_info.appl_name = name;
			v_info.appl_vers = version;
			v_info.platform = platform;
			v_info.message = msg;
			rec.dptr = v_pkt.data;
			rec.dsize = v_assemble_pkt (&v_pkt, &v_info) - V_BASE_SIZE;
			
			if (rc = dbm_store(db,key,rec,DBM_INSERT)) 
				{
				perror("dbm_store");
				exit(1);
				}
			}
		}
	dbm_close(db);
	fclose(ver_file);
	}
