#include <stdio.h>
#include <ncurses.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <signal.h>
#include "mainlib.h"

extern int fifo;
extern int write_log(char *);
extern int exit_program(void);

extern int start_timer();
extern int stop_timer();

int command_exec(char* ins, int boolin)
{
	FILE *log_fifo;	
	char *command;
	int result;
	char postfix[PATH_MAX];
	char tempmessage[STRING_MAX];
	char *message;
	time_t tcurrent;
	char temptime[80];

	pid_t pid;

	stop_timer();
		
	def_prog_mode();
	endwin();
	
	system("clear");

	if(boolin)
	{	
		/*
		if((pid = fork()) == -1)
			return -1;
		
		if (pid == 0) { 				
			sprintf(tempmessage, "pid : %d ->\n", getpid());
			message = (char *)malloc(sizeof(char) * strlen(tempmessage));
			strcpy(message, tempmessage);
			write(fifo, message, strlen(message));
			free(message);

			sprintf(postfix, " >> %s/.tempfifo 2>&1 ", getenv("HOME"), getenv("HOME"));
			strcat(ins, postfix);

			system(ins);
			exit(0);
		}
		
		command = (char *)malloc(strlen(ins) + 2);
		strcat(command , "&");
		result = system(command);

		
		result = -1;
		*/
		
		if (system(ins) == 0) {
			printf("\nPress any key... ");
			getch();
		}
		else {
			printf("\nPress any key... ");
			getch();
		}
		//sigprocmask(SIG_SETMASK, &oldmask, NULL);

	}
	else
	{	
		//sigfillset(&blockmask);
		//sigprocmask(SIG_SETMASK, &blockmask, &oldmask);
		
		if (system(ins) == 0) {		
			if(sprintf(tempmessage, "success : %s\n", ins)<0)
			{
				write_log("command_exec/sprintf1 error");
				return -1;
			}
		}
		else {
			if(sprintf(tempmessage, "success : %s\n", ins)<0)
			{
				write_log("command_exec/sprintf2 error");
				return -1;
			}
		}
		//sigprocmask(SIG_SETMASK, &oldmask, NULL);
	}
	
	reset_prog_mode();
	result = refresh();

	tcurrent = time(NULL);

	if (sprintf(temptime, "%s", ctime(&tcurrent)) < 0) {	
		write_log("command_exec/sprintf3 error");
		return -1;
	}
	temptime[strlen(temptime) - 1] = '\0';
			
	if(sprintf(tempmessage, "success %s: %s\n",temptime, ins)<0)
	{
		write_log("command_exec/sprintf4 error");
		return -1;
	}
	message = (char *)malloc(sizeof(char) * (strlen(tempmessage)+1));
	strcpy(message, tempmessage);
	if(write(fifo, message, strlen(message)) ==-1)
	{
		write_log("command_exec/write error");
		return -1;
	}

	if(sprintf(message, "success %s",ins)<0)
	{
		write_log("vommand_exec/sprintf5");
		return -1;
	}

	write_log(message);
	free(message);

	start_timer();

	return result;
}

