/*
Copyright (c) 2000                      RIPE NCC


All Rights Reserved

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of the author not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.

THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS; IN NO EVENT SHALL
AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

-------------------------------------------------------------------------------
Module Header
Filename          : transferdb.c
Purpose           : Transfer data from Real to backup tables
Author            : Manuel Valente <manuel@ripe.net>
Date              : 20000504
Description       : 
Language Version  : gcc version 2.95.2
OSs Tested        : Solaris 2.6
Command Line      : transferdb
Input Files       : 
Output Files      :
External Programs : mysqld
Problems          : 
To Do             :
Comments          :
-------------------------------------------------------------------------------
*/

static char const rcsid[] = "$Id: transferdb.c,v 1.3 2002/10/24 20:31:32 wilhelm Exp $";

#include "common.h"

/*
-------------------------------------------------------------------------------
Purpose           : Move unused routes from Routes table to Old_Routes
Params            : key, value, DB handle
Returns           : NULL
Comments          : used by g_hash_foreach
*/
void remove_routes (gpointer key, gpointer value, gpointer user_data)
{
        MYSQL* mysql;
        MYSQL_RES *result;
        MYSQL_ROW row;
	unsigned int k;
        char query [1024];

	/* MySQL Handle */
	mysql = (MYSQL*)user_data;
	k = (unsigned int)key;
	
	/* Define query, execute it, use results */
	sprintf (query,"SELECT id,len,crc,route FROM Routes where id = %u",k);
	
        if (mysql_query(mysql,query))
        {
                fprintf(stderr, "Error: %s\n", mysql_error(mysql));
                return;
        };
	
        if (!(result = mysql_use_result(mysql)))
        {
                fprintf(stderr, "Error: %s\n", mysql_error(mysql));
                return;
        };
	
        if (!(row = mysql_fetch_row(result)))
	{
                fprintf(stderr, "Error: %s\n", mysql_error(mysql));
                return;
	};
	
	mysql_free_result(result);

	/* Copy all the data to Old_Routes */		
	sprintf (query,"INSERT INTO Old_Routes (id,len,crc,route) VALUES (%u,%u,\"%s\",\"%s\")",atoi(row[0]),atoi(row[1]),row[2],row[3]);

        if (!(result = mysql_use_result(mysql)))
        {
                fprintf(stderr, "Error: %s\n", mysql_error(mysql));
                return;
        };
	
	sprintf (query,"DELETE FROM Routes WHERE id = %u",k);
	
        if (!(result = mysql_use_result(mysql)))
        {
                fprintf(stderr, "Error: %s\n", mysql_error(mysql));
                return;
        };	
	
	mysql_free_result(result);
	
};

/*
-------------------------------------------------------------------------------
Purpose           : Main - Remove old records
Params            : NULL
Returns           : 0 or errno
*/
int main (int argc, char *argv[])
{
        MYSQL mysql;
        char query [1024];
        time_t timestamp;
        MYSQL_RES *result;
        MYSQL_ROW row;
	GHashTable *routeids;
	unsigned int x;

	unsigned int *k;
	unsigned int *v;
	unsigned int *z;
	
	z= NULL;
	
	/* Initialization */
	routeids = g_hash_table_new (g_int_hash,g_int_equal);

	x = 0;
	
	timestamp = time(NULL);
		
        open_admin_connection (&mysql, MYSQL_HOST);

	/* Get older records */
	sprintf (query,"SELECT id,src,dst,routeid,tstart,tend,numrec FROM Records where tstart < %u", 
	(unsigned int)(timestamp - (DAYS_LIMIT * 86400)));
	
        if (mysql_query(&mysql,query))
        {
                fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
                exit (1);
        };
	
        if (!(result = mysql_use_result(&mysql)))
        {
                fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
                exit (1);
        };

	/* For each found record */
        while ((row = mysql_fetch_row(result)))
        {
		/* Tranfer record in Old_records */
		sprintf (query,"INSERT INTO Old_Records (src,dst,routeid,tstart,tend,numrec) VALUES (%u,%u,%u,%u,%u,%u)",atoi(row[1]),atoi(row[2]),atoi(row[3]),atoi(row[4]),atoi(row[5]),atoi(row[6]));

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

		/* Insert recordid in hash table */
		*z = atoi(row[0]);
		
		if (!g_hash_table_lookup (routeids,z))
		{
			k = malloc(sizeof(int));
			v = malloc(sizeof(int));
		
			*k = atoi(row[0]);
			*v = 1;
		
			g_hash_table_insert (routeids,k,v);
		};

		/* Delete record from actual table */		
		sprintf (query,"DELETE FROM Records WHERE id=%u\n",atoi(row[0]));

		if (mysql_query(&mysql,query))
		{
			fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
			exit (1);
		};		
			
		x++;
        };
	
	printf ("Moved %u records to old table.\n",x);
	
	/* Remove routes that don't appear any more in Records */
	g_hash_table_foreach (routeids,remove_routes,&mysql);
	
	/* Delete records from Old_records that are too old */
	sprintf (query,"DELETE FROM Old_Records WHERE tstart < %u", 
	(unsigned int)(timestamp - (OLD_DAYS_LIMIT * 86400)));

	printf ("Deleted %u records.\n",(unsigned int)mysql_affected_rows(&mysql));
	
        mysql_close(&mysql);

        return (0);
};

	
