#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>

int write_log_go(char*);
int write_log(char *);

int write_log(char *originalstring) {
	sigset_t blockmask;
	sigset_t oldmask;

	char tempstring[1024];
	char temptime[80];
	char *string;
	time_t tcurrent;
	
	if ((sigfillset(&blockmask) == -1) ||
		(sigprocmask(SIG_SETMASK, &blockmask, &oldmask) == -1)) {

		return -1;
	}
	tcurrent = time(NULL);

	if (sprintf(temptime, "%s", ctime(&tcurrent)) < 0) {

		return -1;
	}

	temptime[strlen(temptime) - 1] = '\0';

	if (sprintf(tempstring, "%s::%s::%s\n", temptime, getlogin(), originalstring) < 0) {

		return -1;
	}

	if ((string = (char *)malloc(sizeof(char) * (strlen(tempstring) + 1))) == NULL) {

		return -1;
	}

	if ((strcpy(string, tempstring) == NULL) ||
			(write_log_go(string) < 0)) {
		free(string);
		return -1;
	}

	free(string);
	
	if (sigprocmask(SIG_SETMASK, &oldmask, NULL) == -1){
		return -1;
	}

	return 0;

}
int write_log_go(char *string) {
	
	char *targetstring;
	int key;
	char *lasts;

	key = 19;

	if (initqueue(key) == -1)
		return -1;
	if ((targetstring = (char *)malloc(sizeof(char) * (strlen(string) + 1))) == NULL) {

		return -1;
	}
	//targetstring = strtok_r(string, "\n", &lasts);
	strcpy(targetstring, string);
	if (msgwrite(targetstring, strlen(targetstring)) == -1) {
		return -1;
	}

	free(targetstring);

	return 0;
}
