#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include "mainlib.h"

extern int write_log(char *);

int create_fifo(void);
int delete_fifo(void);
int exit_program(void);
sigset_t blockmask;
sigset_t oldmask;

int fifo;			//로그용 fifo 읽기 0 쓰기1

static void setdoneflag(int signo) {
	exit_program();
}

// 메인 프로그램
int main(int argc, char *argv[]) {
	struct sigaction act;

	act.sa_handler = setdoneflag;
	act.sa_flags = 0;
	if ((sigemptyset(&act.sa_mask) == -1) ||
			(sigaction(SIGINT, &act, NULL) == -1)) {
		perror("Failed to set SIGINT handler");
		return 1;
	}

	sigfillset(&blockmask);
	sigdelset(&blockmask, SIGINT);
	sigdelset(&blockmask, SIGALRM);
	sigprocmask(SIG_SETMASK, &blockmask, &oldmask);
	if ( geteuid() != 0) {
		fprintf(stderr, "Failed run LLS. Your mode is not a supermode\n");
		return -1;
	}	

	write_log("LLS Main Start");

	if (create_fifo() == -1) {
		write_log("Error create_fifo()");
		exit_program();
	}
	if (main_drive() == -1) {
		write_log("Error main_drive()");
		exit_program();
	}



	
	
	exit_program();
	
	
	return 0;
}

int create_fifo(void) {
	char path[STRING_MAX];

	strcpy(path, getenv("HOME"));
	strcat(path, "/");
	strcat(path, ".llslogfifo");
	
	if (access(path, R_OK) != 0 ) {
		if (mkfifo(path, 0666) != 0) {
			endwin();
			printf("Sorry. Failed to create a fifo for log\n");
			return -1;
		}
	}
	else {
		printf("Sorry. Failed to create a fifo for log\n");
		return -1;
	}

	if ((fifo = open(path, O_RDWR)) == -1)
		return -1;

	return 0;
}

int delete_fifo(void) {
	char path[PATH_MAX];
	
	strcpy(path, "rm ");
	strcat(path, getenv("HOME"));
	strcat(path, "/");
	strcat(path, ".llslogfifo");

	close(fifo);
	
	if (system(path) != 0) {
		endwin();
		printf("Failed to delete fifo : %s\n");
		return -1;
	}
	return 0;
}

int exit_program() {
	if (delete_fifo() == -1) {
		endwin();
		write_log("Error delete_fifo()\n");
	}
	if (!isendwin())
		endwin();
	sigprocmask(SIG_SETMASK, &oldmask, NULL);
	
	write_log("LLS Exit");

	exit(1);
}
