#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h> 
#include <sys/wait.h>
#include <sys/stat.h> 
#include <fcntl.h>
#include <string.h>


#ifndef LAUNCHER_EXE
#define LAUNCHER_EXE "ketm"
#endif

int main() {
	pid_t p;
	char *exename;
	char logf[512];
	char exe[512];

	FILE *c = fopen("launcher.conf", "r");
	if (c!=NULL) {
		exename = malloc(sizeof(char)*256);
		fscanf(c, "%s", exename);
	} else {
		exename = LAUNCHER_EXE;	
	}
        strcpy(logf, exename);
        strcat(logf,"_launcher.log");
	

	if (p=fork()==0) {		//Child process
		// redirect output to the log file
		FILE *f = freopen(logf,"w",stderr); 
		f = freopen(logf,"w",stdout);

		// set the file to start 
		char *av;
		av = malloc(sizeof(char)*100);
        	getcwd(av,100);
        	strcat(av, "/");
        	strcat(av, exename);


		// start it
		printf("[ Starting ]---{ %s }-----------------------\n", av);
		execl(av,av,NULL);
		printf("FAILED !\n");
		return 1;
	} else {		//Parent process
		// Wait the child process to finish
		wait(&p);

		// restart the caanoo menu
		chdir("/usr/gp2x");
		execl("/usr/gp2x/gp2xmenu", "/usr/gp2x/gp2xmenu", NULL);
		printf("Could not execute %s\n", "/usr/gp2x/gp2xmenu");
		return 1;
	}
}
