#import <Cocoa/Cocoa.h>

#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

/*
 open a connection to CERT
 pipe the contents of rimagedata.bin to CERT
 again
 again
 close connection
*/

int main()
{
	[NSApp sharedApplication];
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSSocketPort  *socketPort = [[NSSocketPort alloc] initRemoteWithTCPPort:80 host:@"132.239.147.100"];

	int fd = [socketPort socket];
	
	if( -1 == fd )
	{
//		NSLog( @"Unable to open port. Bad file descriptor." );
//		return -3;
		
		
		/* Assume servername is a string that contains the address */
		/* e.g:  irc.gate.net */
		/* Assume port is a string that contains the port number */
		/* eg: 6666 */
		struct sockaddr_in serveradd;
		//char port[8];
		int csock;
		//int sockaddr_size;
		struct hostent *hp; 
		
		csock = socket( AF_INET, SOCK_STREAM, 0 );
		if( csock < 0 )
		{
			NSLog( @"Error creating a socket." );
			return -5;
		}
		
		hp = gethostbyname( "localhost" );
//		hp = gethostbyname( "10.0.3.39" );
		if( hp == 0 )
		{
			NSLog( @"Unknown host." );
			return -4;
		} 
		
		serveradd.sin_family = AF_INET;
		serveradd.sin_port = htons( 15555 ); 
		memcpy( (char *)&serveradd.sin_addr, (char*)hp->h_addr, hp->h_length );
		//serveradd.sin_addr.s_addr = inet_addr("132.239.147.100"); 
		//	if( !inet_aton( "132.239.147.100", &(serveradd.sin_addr) ) )
		//	{
		//		NSLog( @"Unable to convert RUBIOS host address." );
		//		[self setStatus:@"Unable to convert RUBIOS host address."];
		//		return;
		//	}
		memset( (char *)&serveradd.sin_zero, 0, sizeof(serveradd.sin_zero) );
		
		//sendto(s,msg,sizeof(msg),0,(struct sockaddr*)&addr,sizeof(addr)); 
		if( connect( csock, (struct sockaddr *)&serveradd, sizeof(serveradd) ) < 0 )
		{
			NSLog(@"Error connecting");
			return -3;
		}
		fd = csock;
	}
	
	NSFileHandle *portHandle = [[NSFileHandle alloc] initWithFileDescriptor:fd closeOnDealloc:YES];
	
	if( !portHandle )
	{
		NSLog( @"Unable to open port." );
		return -2;
	}
	
	NSData *data = [NSData dataWithContentsOfFile:@"/tmp/rimagedata.bin"];
	if( 0 == [data length] )
	{
		NSLog( @"Unable to open data file." );
		return -1;
	}
	
	for( int cnt = 2000; cnt > 0; --cnt )
	{
		[portHandle writeData:data];
		if( 0 == (cnt % 100) )
			NSLog( @"Sent %d images.", cnt );
	}
//	[portHandle writeData:data];
//	[portHandle writeData:data];
	[portHandle closeFile];
	[portHandle release];
	[pool release];
	return 0;
}
