#include <stdlib.h>
#include <curl/curl.h>
#include <apr_strings.h>

#include "htdavlock.h"

#ifndef HTTP_NO_CONTENT
#define HTTP_NO_CONTENT 204
#endif

int
htdavlock_httpclient(apr_pool_t *p, const char *url,
		     const char *locktoken, const char *user)
{
	CURL *curl;
	CURLcode rv;
	long status;
	char e[CURL_ERROR_SIZE];
	struct curl_slist *list;
	char *locktoken_hdr;
	int retval = -1;

	if ((curl = curl_easy_init()) == NULL) {
		warnx("curl_easy_init() failed");
		goto out;
	}

	curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, e);
	curl_easy_setopt(curl, CURLOPT_VERBOSE, 0L);
	curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L);
	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
	curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3L);
	curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
	curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "UNLOCK");
	curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
	curl_easy_setopt(curl, CURLOPT_USERNAME, user);
	curl_easy_setopt(curl, CURLOPT_URL, url);
	curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);

	locktoken_hdr = apr_pstrcat(p, "Lock-Token: <opaquelocktoken:",
				    locktoken, ">", NULL);
	list = curl_slist_append(NULL, locktoken_hdr);
	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
	  
	switch (rv = curl_easy_perform(curl)) {
	case CURLE_OPERATION_TIMEDOUT: /* FALLTHROUGH */
		warnx("UNLOCK %s timeout", url);
		break;
	case CURLE_OK:
		if ((rv = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, 
					    &status)) != CURLE_OK) {
			warnx("curl_easy_getinfo failed: %s", e);
			break;
		}

		if (status != HTTP_NO_CONTENT) {
			warnx("UNLOCK %s got status %ld", url, status);
			break;
		}

		retval = 0;
		break;
	default:
		warnx("UNLOCK %s error: %s", url, e);
		break;
	}

out:
	return retval;
}
