/*
	Socket Scripter for ezSockets is designed to allow two-way socket 
	communication.  Everything that the server sends back will be logged 
	to a file, while the scripter will connect completely according to a 
	pre-scripted file. Usage:

		sscripter [in script]

	There are four commands that this scripter currently understands:

		#comment
		log [text|binary|off]
		connect [host] [port] [mode]
		listen [port] [mode]
		disconnect
		sleep [time]
		send [data]

	Note that with logging, binary will not reformat the output in any way
	text will reformat characters below 32 to special characters.

	Mode is optional on connect.  If it is set to one, UDP will be used.
	Otherwise TCP will be used.

	Where data is a C-style string, back-slashes perform the same function 
	here as in C.  You may use \n, \t, \r, \f, \b, \\, \', \", 
	\[octal number].  An example of a script would be:

		#sample program
		log binary
		connect www.google.com 80
		sleep 100
		send GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n
		sleep 1000
		disconnect

	Copyright 2006 Charles Lohr under the MIT/X11 License.
*/


#include "ezSockets.h"
#include "Util.h"
#include <iostream>

using namespace std;

int main( int argc, char ** argv )
{
	if( argc != 2 )
	{
		//General comment
		cout<<"Socket Scripter for ezSockets is designed to allow two-way socket"<<endl;
		cout<<"communication.  Everything that the server sends back will be logged "<<endl;
		cout<<"to a file, while the scripter will connect completely according to a "<<endl;
		cout<<"pre-scripted file. Usage:"<<endl;
		cout<<""<<endl;
		cout<<"	sscripter [in script]"<<endl<<endl;
		cout<<"There are four commands that this scripter currently understands:"<<endl;
		cout<<""<<endl;
		cout<<"	#comment"<<endl;
		cout<<"	log [text|binary|off]"<<endl;
		cout<<"	connect [host] [port] [mode]"<<endl;
		cout<<"	listen [port] [mode]"<<endl;
		cout<<"	disconnect"<<endl;
		cout<<"	sleep [time]"<<endl;
		cout<<"	send [data]"<<endl;
		cout<<""<<endl;
		cout<<"Note that with logging, binary will not reformat the output in any way"<<endl;
		cout<<"text will reformat characters below 32 to special characters."<<endl;
		cout<<""<<endl;
		cout<<"Mode is optional on connect.  If it is set to one, UDP will be used."<<endl;
		cout<<"Otherwise TCP will be used."<<endl<<endl;
		cout<<"Where data is a C-style string, back-slashes perform the same function "<<endl;
		cout<<"here as in C.  You may use \\n, \\t, \\r, \\f, \\b, \\\\, \\\', \\\", "<<endl;
		cout<<"\\[octal number].  An example of a script would be:"<<endl;
		cout<<""<<endl;
		cout<<"	#sample program"<<endl;
		cout<<"	log binary"<<endl;
		cout<<"	connect www.google.com 80"<<endl;
		cout<<"	sleep 100"<<endl;
		cout<<"	send GET / HTTP/1.1\\r\\nHost: www.google.com\\r\\n\\r\\n"<<endl;
		cout<<"	sleep 1000"<<endl;
		cout<<"	disconnect"<<endl<<endl;
		cout<<"Copyright 2006 Charles Lohr under the MIT/X11 License."<<endl;
		return 0;
	}

	//Open the file and check to see if it failed
	FILE * f = fopen( argv[1], "rb" );
	if( !f )
	{
		cerr<<"ERROR: Cannot open input file!"<<endl;
		return -1;
	}

	ezSockets	sSocket;
	int			iLogMode = 0;
	int			iLine = 0;

	//While we can keep reading the script file
	while( !feof( f ) && !ferror( f ) )
	{
		//Get a line and systematically compare to see what the line says to do
		string sLine = ReadFLine( f );
		iLine++;
		if( sLine.substr( 0, 1 ).compare( "#" ) == 0 )
		{
			//Comment
		} else if( sLine.substr( 0, 3 ).compare( "log" ) == 0 )
		{
			if( sLine.length() < 5 )
			{
				cerr<<"Error on line "<<iLine<<" log needs a parameter."<<endl;
				continue;
			}
			if( sLine.substr( 4, 4 ).compare( "text" ) == 0 )
				iLogMode = 1;
			else if( sLine.substr( 4, 6 ).compare( "binary" ) == 0 )
				iLogMode = 2;
			else if( sLine.substr( 4, 3 ).compare( "off" ) == 0 )
				iLogMode = 0;
			else
				cerr<<"Error on line "<<iLine<<" invalid log type."<<endl;
		} else if( sLine.substr( 0, 7 ).compare( "connect" ) == 0 )
		{
			char sHostName[1024];
			int iPort;
			int iUDP = 0;

			if( sLine.length() < 8 )
			{
				cerr<<"Error on line "<<iLine<<" connect needs at least two parameters."<<endl;
				continue;
			}

			if( sscanf( sLine.substr( 8 ).c_str(), "%s %d %d", sHostName, &iPort, &iUDP ) < 2 )
			{
				cerr<<"Error on line "<<iLine<<" connect needs atleast two parameters."<<endl;
				continue;
			}
			
			//Decide on a connection type 
			if( iUDP == 1 )
			{
				sSocket.mode = ezSockets::skUDP;
				sSocket.Create( IPPROTO_UDP, SOCK_DGRAM );
			} else if( iUDP == 0 )
			{
				sSocket.mode = ezSockets::skGeneral;
				sSocket.Create();
			} else
			{
				cerr<<"Error on line "<<iLine<<" Invalide socket mode."<<endl;
				continue;
			}

			//Then connect.  Only report connection if logging is on
			sSocket.bBlocking = true;
			if( sSocket.Connect( sHostName, iPort ) )
			{
				if( iLogMode )
					cout<<"Connection Established."<<endl;
			} else
				if( iLogMode )
					cout<<"Connection Failed."<<endl;
		} else if( sLine.substr( 0, 6 ).compare( "listen" ) == 0 )
		{
			int iPort;
			int iUDP = 0;

			if( sLine.length() < 6 )
			{
				cerr<<"Error on line "<<iLine<<" connect needs at least two parameters."<<endl;
				continue;
			}

			if( sscanf( sLine.substr( 7 ).c_str(), "%d %d", &iPort, &iUDP ) < 2 )
			{
				cerr<<"Error on line "<<iLine<<" connect needs atleast two parameters."<<endl;
				continue;
			}
			
			//Decide on a connection type 
			if( iUDP == 1 )
			{
				sSocket.mode = ezSockets::skUDP;
				sSocket.Create( IPPROTO_UDP, SOCK_DGRAM );
			} else if( iUDP == 0 )
			{
				sSocket.mode = ezSockets::skGeneral;
				sSocket.Create();
			} else
			{
				cerr<<"Error on line "<<iLine<<" Invalid socket mode."<<endl;
				continue;
			}

			//Then connect.  Only report connection if logging is on
			sSocket.bBlocking = true;
			if( !sSocket.Bind( iPort ) )
			{
				cerr<<"Could not bind to port "<<iPort<<endl;
				continue;
			}

			if( !sSocket.Listen() )
			{
				cerr<<"Could not listen on port."<<endl;
				continue;
			}
			ezSockets * s = sSocket.Accept();
			sSocket.Close();
			delete &sSocket;
			memcpy( &sSocket, s, sizeof( ezSockets ) );
		} else if( sLine.substr( 0, 5 ).compare( "sleep" ) == 0 )
		{
			if( sLine.length() < 6 )
			{
				cerr<<"Error on line "<<iLine<<" sleep needs a parameter."<<endl;
				continue;
			}
			XSleep( atoi( sLine.substr( 6 ).c_str() ) );
		} else if( sLine.substr( 0, 5 ).compare( "disconnect" ) == 0 )
		{
			sSocket.Close();
		} else if( sLine.substr( 0, 4 ).compare( "send" ) == 0 )
		{
			if( sLine.length() < 5 )
			{
				cerr<<"Error on line "<<iLine<<" sleep needs a parameter."<<endl;
				continue;
			}

			string sToSend = ConvertToUnformatted( sLine.substr( 5 ) );
			sSocket.SendData( sToSend.c_str(), sToSend.length() );
		}

		//If we have an open socket and we can get data from it, show all the data!
		if( sSocket.Check() )
			while( sSocket.CanRead() || sSocket.DataAvailable() )
			{
				char b;
				sSocket.ReadLeftover( &b, 1 );
				if( iLogMode == 2 )
					cout<<b;
				else
				{
					string st;
					st += b;
					cout<<ConvertToCFormat(st);
				}
			}
	}

	return 0;
}

/* 
 * (c) 2006 Charles Lohr
 * All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, and/or sell copies of the Software, and to permit persons to
 * whom the Software is furnished to do so, provided that the above
 * copyright notice(s) and this permission notice appear in all copies of
 * the Software and that both the above copyright notice(s) and this
 * permission notice appear in supporting documentation.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
 * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
 * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR 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.
 */
