#include "compat.h"
#include "net.h"

#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif

#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 255
#endif

void backuppc_notify(const char *host, const int port, const char *overridehostname) {
	static char *hostname = NULL;
	char cmdbuf[8192], *cmdbuf_p;
	size_t hostname_len;
	ssize_t send_ret;
	int chk_ret;
	int sockfd;

	if (!host || port <= 0) {
		return;
	}

	if (overridehostname) {
		hostname = (char *) overridehostname;
	}

	if (!hostname) {
		hostname_len = HOST_NAME_MAX + 1;
		hostname = malloc(hostname_len);
		if (hostname) {
			chk_ret = gethostname(hostname, hostname_len);
			if (chk_ret < 0) {
				free(hostname);
				hostname = NULL;
			}
		}
	}

	if (!hostname) {
		return;
	}

	sockfd = net_connect_tcp(host, port);
	if (sockfd >= 0) {
		/* XXX: Authentiation ? */

		/* Send hostname */
		chk_ret = snprintf(cmdbuf, sizeof(cmdbuf), "HOST %s\n", hostname);
		if (chk_ret < sizeof(cmdbuf)) {
			cmdbuf_p = cmdbuf;

			while (chk_ret) {
				send_ret = send(sockfd, cmdbuf_p, chk_ret, 0);

				if (send_ret < 0) {
					break;
				}

				cmdbuf_p += send_ret;
				chk_ret -= send_ret;
			}
		}

		net_close(sockfd);
	}

	if (overridehostname) {
		hostname = NULL;
	}

	return;
}
