#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <time.h>

void xfree (char **p)
{
	free (*p);
	*p = NULL;
}

void xdup (char *src, char **dst)
{
	if (*dst)
		xfree (dst);

	*dst = strdup(src);

	if (strlen(*dst) && (*dst)[strlen(*dst) - 1] == 0x0A)
		(*dst)[strlen(*dst) - 1] = 0;
	if (strlen(*dst) && (*dst)[strlen(*dst) - 1] == 0x0D)
		(*dst)[strlen(*dst) - 1] = 0;
}

char xrandch (void)
{
	return rand() % ('z' - 'a') + 'a';
}

char *xrand (void)
{
	static char buf[6];
	size_t i;

	for (i = 0; i < 5; i++)
		buf[i] = xrandch();

	buf[5] = 0;
	return buf;
}

void xml (char *uin, char *disp)
{
	fprintf (stdout, "<iq type=\"set\" id=\"%s\" >\n"
	    "<query xmlns=\"jabber:iq:roster\">\n"
	    "<item name=\"%s\" jid=\"%s@gg.chrome.pl\" />\n"
	    "</query>\n"
	    "</iq>\n"
	    "\n"
	    "<presence type=\"subscribe\" to=\"%s@gg.chrome.pl\" />\n"
	    "\n",
	    xrand(), disp, uin, uin);
}

int main (void)
{
	char *uin = NULL, *disp = NULL;

	srand (getpid() | time(NULL));

	for (;;) {
		char str[256];

		fgets (str, sizeof(str), stdin);
		if (feof(stdin))
			break;

		if (!strncmp(str, "Uin: ", 5))
			xdup (str + 5, &uin);
		else if (!strncmp(str, "Display: ", 9)) {
			xdup (str + 9, &disp);
			xml (uin, disp);
		}
	}

	if (uin)
		xfree (&uin);

	if (disp)
		xfree (&disp);

	return 0;
}
