#include "gtkicq.h"
#include <stdio.h>
#include <stdlib.h>

#include <unistd.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/time.h>

#include <fcntl.h>
#include <time.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <sys/wait.h>
#include <signal.h>

#include <gtk/gtk.h>
#include "gtkfunc.h"

#include "tcp.h"

void restart( struct sokandlb *data )
{
	int cx;
	struct sockaddr_in addr;
	int l = 1;
	int temp_sok;
	int our_sok;
	int connecting;
	
	ProgressData *pdata = NULL;

#ifdef TRACE_FUNCTION
	printf( "restart\n" );
#endif

	icq_change_status( data->sok, STATUS_OFFLINE, data );
	Quit_ICQ( data->sok );
	for( cx = 0; cx < Num_Contacts; cx ++ )
	{
		Contacts[ cx ].last_status = Contacts[ cx ].status;
		Contacts[ cx ].status = STATUS_OFFLINE;
	}
	Show_Quick_Status( data );
	seq_num = 0;
	memset( serv_mess, FALSE, 1024 );
	close( data->sok );

	Done_Login = FALSE;

	data->sok = Connect_Remote( server, remote_port, STDERR );

	if ( ( data->sok == -1 ) || ( data->sok == 0 ) ) 
	{
		printf( "Couldn't establish connection, %d\n" , data->sok );
		exit( 1 );
	}

	gdk_input_remove( udp_gdk_input );
	udp_gdk_input = gdk_input_add( data->sok, GDK_INPUT_READ, (GdkInputFunction) icq_refresh, data );

	addr.sin_addr.s_addr = htonl( INADDR_ANY );
	addr.sin_family = AF_INET;
	addr.sin_port = htons( our_port );
	
	temp_sok = socket( AF_INET, SOCK_STREAM, 0 );
	setsockopt( temp_sok, SOL_SOCKET, SO_REUSEADDR, &l, 4 );

	our_sok = bind( temp_sok, (struct sockaddr *)&addr, sizeof( addr ) );
	if( -1 == our_sok )
	{
		printf( "Could not bind to socket, port %ld\n", our_port );
		exit( 1 );
	}

	our_sok = temp_sok;
	
	if( -1 == listen( our_sok, 10 ) )
	{
		printf( "Cannot listen to socket, port %ld\n", our_port );
		exit( 1 );
	}

	l = sizeof( addr );

	gdk_input_remove( tcp_gdk_input );
	tcp_gdk_input = gdk_input_add( our_sok, GDK_INPUT_READ, (GdkInputFunction) TCPAcceptIncoming, data );

	connecting = show_wait( "Connecting to Server", pdata );
	gtk_statusbar_push( GTK_STATUSBAR( statusbar ), 1, " Connecting to Server..." );

	while( gtk_events_pending() )
		gtk_main_iteration();

	Login( data->sok, UIN, &passwd[0], our_ip, our_port );

	return;
}
