
#include "common.h"
#include "digest.h"


void convert_route (char *route)
{
        char buf [512];
        char *p;
        unsigned int ip;
        
        p = strtok (route," ");
        sscanf (p,"%X",&ip);
        
        sprintf (buf,"%u",ip);
        
        while ((p = strtok (NULL," ")))
        {
                sscanf (p,"%X",&ip);
                
                sprintf (buf,"%s %u",buf,ip); 
        };
        
        strcpy (route,buf);
};

void fillroutes (MYSQL *mysql, char *vbye_path)
{
	FILE *fd;
	char buf [1024];
	char *p;
	int id,len;
	char xbuf [30];
	char route [512];
	char crc [32];
	char query [512];
	unsigned int src,dst;

	fd = NULL;	

	if((fd = fopen(vbye_path,"rb")) == NULL)
	{
		fprintf(stderr, "Cannot open %s: %s\n", vbye_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," ");
		id = atoi(p);
		
		if (id == 0) continue;
		
		p = strtok (NULL," ");		
		strcpy (xbuf,p);
		sscanf (xbuf,"%X",&src);
		
		p = strtok (NULL," ");		
		strcpy (xbuf,p);
		sscanf (xbuf,"%X",&dst);
		
		p = strtok (NULL," ");
		len = atoi(p);

		p = strtok (NULL,"");
		strcpy (route,p);
		
                convert_route (route);
				
		crc_calc (route,crc);
			
		sprintf (query,"INSERT INTO Routes (id,len,crc,route) VALUES (%u,%u,\"%s\",\"%s\")",id,len,crc,route);

		if (mysql_query(mysql,query))
		{
			fprintf(stderr, "Error: %s\n", mysql_error(mysql));
		};

		//printf ("%s\n",query);
		
	};

	fclose (fd);	
};

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

	fillroutes(&mysql,VBYE);
	
	mysql_close(&mysql);
	
	return (0);
};
