using SSL;
using Posix;

// Static fields
static string host;
static int port = 443;

private const OptionEntry[] options = {
	{ "ip", 'i', 0, OptionArg.STRING,
	  ref host, "Server IP address [default: 74.125.232.115]", "I" },
	{ "port", 'p', 0, OptionArg.INT,
	  ref port, "Server SSL port number [default: 443]", "P" },
	{ null }
};

int main(string[] args) {
	host = "";
    try{
		var opt_context = new OptionContext(" - OpenSSL Test");
		opt_context.set_help_enabled (true);
		opt_context.add_main_entries (options, null);
		opt_context.parse (ref args);
	} catch (OptionError e) {
		GLib.stderr.printf("option parsing failed: %s\n", e.message);
		GLib.stderr.printf ("\nTry --help.\n");
		return 1;
	}

	if (host == "") {
		host = "74.125.232.115";
		GLib.stderr.printf ("No host address specified, using %s\n\n", host);
	}
	
	SSL.library_init();
	var ctx = new SSL.Context(SSLv3_method());
	var c = new SSL.Connection(ctx);

    int s = Posix.socket(Posix.AF_INET, Posix.SOCK_STREAM, 6);
//    int flags = fcntl (s, F_GETFL, 0);
//    fcntl (s, F_SETFL, flags | O_NONBLOCK);
	GLib.stdout.printf("socket: %d\n", s);
	c.set_fd(s);
	GLib.stdout.printf("ssh socket\n");
	
	var sa = SockAddrIn();
	sa.sin_family = AF_INET;
	sa.sin_port =  htons((uint16) port);
//	sa.sin_addr = InAddr();
	sa.sin_addr.s_addr = inet_addr(host);
	int connected = c.connect(&sa);
	GLib.stdout.printf("connected: %d\n", connected);
	var request = "GET / HTTP/1.0\r\nHost: google.com\r\n\r\n";
//	try {
		int sent = c.send(request, request.length);
		GLib.stdout.printf("sent: %d\n", sent);
		uint8* buf = new uint8[65536];
		int received = c.recv(buf, 65536);
		GLib.stdout.printf("received: %d\n", received);
		if (received > 0) {
			GLib.stdout.printf((string)buf);
		}
//	} catch (SSLException e) {
//		GLib.stderr.printf("SSL error: %s\n", e.message);
//	}
	c.shutdown();
	GLib.stdout.printf("All done.\n");
	return 0;
}
