#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/msg.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <pthread.h>
#include "logsendfunction.h"
#include "restart.h"

#define MAXSIZE 4096

typedef struct {
	long mtype;
	char mtext[MAXSIZE];
} mymsg_t;

int main(int argc, char *argv[]) {
	int key;
	mymsg_t mymsg;
	int size;
	char *lasts;
	char *string;
	int fd;
	pid_t pid;
	
	if (geteuid() != 0) {
		fprintf(stderr, "Failed to run demon. Use 'sudo' or 'su'.\n");
		return 1;
	}

	printf("Start LLS log demon...");
	
	switch(fork()) {
	case -1 :
		exit(1);
	case 0 :
		setsid();
		break;
	default:
		printf("[OK]\n");
		exit(0);
	}

	key = 19;
	if (initqueue(key) == -1) {
		perror("Failed to initialize message queue");
		return 1;
	}
	for ( ; ; ) {
		if ((fd = open("/etc/lls/llslogfile", (O_CREAT | O_APPEND | O_WRONLY ), (S_IRUSR|S_IWUSR)) == -1)) {
			perror("Failed to read message queue");
			break;
		}

		if ((size = msgread(&mymsg, MAXSIZE)) == -1) {
			perror("Failed to read message queue");
			break;
		}
		if (r_write(fd, mymsg.mtext, size) == -1) {
			perror("Failed to write to standard output");
			break;
		}
		close(fd);
	}
	
	return 0;
}
