#include <libsoup/soup.h>
#include <stdio.h>
#include <stdlib.h>

static void souptest_authenticate(SoupSession *sess, SoupMessage *msg,
				  SoupAuth *auth, gboolean retrying, gpointer data)
{
	gboolean *done = data;
	char *username = getenv("NTLM_USER");
	char *pass = getenv("NTLM_PASS");
	char * scheme = soup_auth_get_scheme_name(auth);
	printf("scheme %s\n", scheme);
	if (getenv("NTLM_ONLY") && strcmp(scheme, "NTLM"))
		return;
	if (!username || !pass) {
		fprintf(stderr, "Need to set $NTLM_USER and $NTLM_PASS environment variables\n");
		return;
	}
	printf("authenticating, %sretrying\n", retrying?"":"not ");
	soup_auth_authenticate (auth, username, pass);
}

int main(int argc, char **argv)
{
	SoupSession *sess;
	SoupMessage *msg;
	SoupLogger *logger;
	guint status;
	gboolean authenticated = FALSE;

	if (argc != 2) {
		fprintf(stderr, "One argument required; the URL\n");
		exit (1);
	}

        g_thread_init (NULL);
        g_type_init ();

	sess = soup_session_sync_new_with_options(SOUP_SESSION_USE_NTLM, TRUE, NULL);
	g_signal_connect (sess, "authenticate",
			  G_CALLBACK(souptest_authenticate), &authenticated);

	logger = soup_logger_new(SOUP_LOGGER_LOG_HEADERS, -1);
	soup_session_add_feature(sess, SOUP_SESSION_FEATURE(logger));

	msg = soup_message_new("GET", argv[1]);

	soup_message_headers_append (msg->request_headers,
				     "User-Agent", "libews/0.1");

	status = soup_session_send_message(sess, msg);
	printf("status %d\n", status);
}

char *rq = "<Autodiscover xmlns='http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006'><Request><EMailAddress>%s</EMailAddress><AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a</AcceptableResponseSchema></Request></Autodiscover>";
