/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "mysql.h"

/* START CONFIGURATION */
#define DB_SERVER "localhost"
#define DB_USERNAME "root"
#define DB_PASSWORD ""
#define DB_DATABASE "Test"
/* END CONFIGURATION */

void dbimport(char *csvfnm, int fromcol, int tocol, int countrycol, char *tblnam)
{
    FILE *fp;
    MYSQL *handle;
    int n,col,l;
    char *p;
    char sqlcmd[200],line[100],ip1[11],ip2[11],country[3];
    handle = mysql_init(NULL);
    if(handle == NULL)
    {
        printf("MySQL error: %s", mysql_error(handle));
        exit(1);
    }
    if(!mysql_real_connect(handle, DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE, 0, NULL, 0))
    {
        printf("MySQL error: %s", mysql_error(handle));
        exit(1);
    }
    sprintf(sqlcmd,"DROP TABLE %s", tblnam);
    if(mysql_query(handle, sqlcmd))
    {
        /* we will end here first time */
    }
    sprintf(sqlcmd,"CREATE TABLE %s (id INTEGER NOT NULL, ip1 NUMERIC(10,0), ip2 NUMERIC(10,0), country CHAR(2), PRIMARY KEY(id))", tblnam);
    if(mysql_query(handle, sqlcmd))
    {
        printf("MySQL error: %s", mysql_error(handle));
        exit(1);
    }
    sprintf(sqlcmd,"CREATE INDEX ixip1 ON %s (ip1)",tblnam);
    if(mysql_query(handle, sqlcmd))
    {
        printf("MySQL error: %s", mysql_error(handle));
        exit(1);
    }
    sprintf(sqlcmd,"CREATE INDEX ixip2 ON %s (ip2)",tblnam);
    if(mysql_query(handle, sqlcmd))
    {
        printf("MySQL error: %s", mysql_error(handle));
        exit(1);
    }
    fp = fopen(csvfnm,"r");
    n = 0;
    while(fgets(line,sizeof(line),fp))
    {
        n++;
        col = 1;
        p = strtok(line, ",");
        while(p != NULL)
        {
            if(col == fromcol)
            {
                l = strlen(p) - 2;
                strncpy(ip1, p + 1, l);
                ip1[l] = '\0';
            }
            if(col == tocol)
            {
                l = strlen(p) - 2;
                strncpy(ip2, p + 1, l);
                ip2[l] = '\0';
            }
            if(col == countrycol)
            {
                l = strlen(p) - 2;
                strncpy(country, p + 1, l);
                country[l] = '\0';
            }
            p = strtok(NULL, ",");
            col++;
        }
        sprintf(sqlcmd,"INSERT INTO %s VALUES(%d,%s,%s,'%s')",tblnam,n,ip1,ip2,country);
        if(mysql_query(handle, sqlcmd))
        {
            printf("MySQL error: %s", mysql_error(handle));
            exit(1);
        }
    }
    fclose(fp);
    mysql_close(handle);
}

int main()
{
    dbimport("ip-to-country.csv",1,2,3,"whi");
    dbimport("GeoIPCountryWhois.csv", 3, 4, 5, "mm");
    return 0;
}
