
#include "common.h"



void fillrecords (MYSQL *mysql, char *boxpath, char *rbyt_path)
{
	FILE *fd;
/*	char buf [1048576];*/
	char buf [1500000];
	char *p;
	char xbuf [32];
	char query [512];
	unsigned int src,dst,timestamp,id,tstart,tend,numrec;
	GHashTable *ranges;
	
	int *pz;
	
	tend = 0;
		
	ranges  = g_hash_table_new (g_int_hash,g_int_equal);
	
	get_ranges (ranges,boxpath);

	fd = NULL;	

	if((fd = fopen(rbyt_path,"rb")) == NULL)
	{
		fprintf(stderr, "Cannot open %s: %s\n", rbyt_path, strerror(errno));
		exit (1);
	};
	
	while (!feof(fd))
	{
		if(fgets(buf, sizeof(buf), fd) == NULL) continue;
		buf[strlen(buf)-1] = '\0';
		
		p = strtok (buf," ");
		p = strtok (NULL," ");
		
		p = strtok (NULL," ");
                strcpy (xbuf,p);
                sscanf (xbuf,"%X",&src);
		
		if (!(pz = g_hash_table_lookup (ranges,&src)))
		{
			fprintf (stderr, "Unknown IP %u\n",src);
			continue;
		};
		
		src = *(int*)pz;
		
		p = strtok (NULL," ");
                strcpy (xbuf,p);
                sscanf (xbuf,"%X",&dst);

		if (!(pz = g_hash_table_lookup (ranges,&dst)))
		{
			fprintf (stderr, "Unknown IP %u\n",dst);
			continue;
		};
		
		dst = *(int*)pz;
		
		p = strtok (NULL," ");
		timestamp = atoi(p);
		
		tstart = 0;
				
		p = strtok (NULL," ");
		
		printf ("%u %u %u\n",src,dst,timestamp);

		while ((p = strtok (NULL," ")))
		{
			id = atoi(p);

/*			if (id == 0) break; */

			
			tstart = (tstart==0) ? timestamp : (tend +1);

			p = strtok (NULL," ");
			tend = atoi(p);
			
			p = strtok (NULL," ");
			numrec = atoi(p);

			/* Mysql doesn't support id=0, if found, skip the entry 
			   but do not give up on this range completely! */

			if (id != 0) {
				sprintf (query, "INSERT INTO Records (src,dst,routeid,tstart,tend,numrec) VALUES (%u,%u,%u,%u,%u,%u)",src,dst,id,tstart,tend,numrec);
				//printf ("%s\n",query);
			
				if (mysql_query(mysql,query))
				{
					fprintf(stderr, "Error: %s\n", mysql_error(mysql));
				};
			}
		};		
	};

	fclose (fd);	
};

int main (int argc, char *argv[])
{
	MYSQL mysql;

	/* default, update "localhost" server */
	open_admin_connection (&mysql, MYSQL_HOST);

	fillrecords(&mysql,PATHBOXES,RBYT);
	
	mysql_close(&mysql);
	
	return (0);	
};
