#include "exec.h"
#include "entry.h"

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

void umount_all()
{
	DIR           *d;
  struct dirent *dir;
  d = opendir("/tmp/mountpoint/");
  if (d)
  {
    while ((dir = readdir(d)) != NULL)
    {
			struct stat buf;
			char path[256];
			if(!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, "..")) continue;
			sprintf(path, "/tmp/mountpoint/%s", dir->d_name);
			if(lstat(path, &buf))
			{
				fprintf(stderr, "Error can't stat '%s'", path);
				perror(" ");
				continue;
			}
			if(S_ISDIR(buf.st_mode))
			{
				if(umount(path))
				{
					fprintf(stderr, "Unable to unmount '%s'", path);
					perror(" ");
				}
			}
    }

    closedir(d);
  }
}

int file_exists(const char* file)
{
	FILE* f=fopen(file, "r");
	if(!f)
	{
		fprintf(stderr, "Erreur fichier '%s' ", file);
		perror(" ");
		return -1;
	}
	fclose(f);
	return 0;
}

int os_exec(const char* base, os_entry_t* os)
{
	int pid;
	char cmd[4096];//--initrd=/initrd.img
	char kernel[512], initrd[512]="", root_fs[512], root_path[512], root_type[16], cmdline[2048];
	
	sprintf(cmdline, "--append=\"%s single root_fs=%s root_path=%s \"", os->append, os->rootfs, root_path);
	
	sprintf(kernel, "/tmp/mountpoint/%s/%s/%s", base, os->location, os->kernel);
	if(file_exists(kernel)) return -1;
	
	
	sprintf(initrd, "--initrd=/initrd.img");
		
	sprintf(cmd, "kexec -l %s --initrd=/initrd.img  --append=root=/dev/sda1", kernel, cmdline);
	printf("%s\n",cmd);
	/*if(pid=fork())
	{
		int ret=1, rpid;
		rpid=waitpid(pid, &ret, 0);
		if(ret && pid==rpid)
		{
			fprintf(stderr, "Unable to load kexec : %s\nexitting...\n", strerror(ret));
			return -1;
		}
	}
	else
	{
		if(execl("/usr/sbin/kexec", "/usr/sbin/kexec",  "-l",  kernel, initrd, cmdline, NULL))
		{
			fprintf(stderr, "Unable to exec kexec");
			perror(" ");
		}
	}*/
	
	//sleep(10);
	system(cmd);
	//system("umount -a");
	/*system("umount /");
	system("umount /tmp/mountpoint/sdb1");
	system("umount /proc");
	system("umount /sys");
	system("umount /dev");*/
	
	//umount_all();
	//sleep(10);
	//system("umount -a");
	/*if(pid=fork())
	{
		int ret;
		waitpid(pid, &ret, 0);
		if(ret)
		{
			fprintf(stderr, "Unable to kexec : %s\nexitting...\n", strerror(ret));
			return -1;
		}
		//unreachable code
	}
	else
	{
		if(!execl("/usr/sbin/kexec", "/usr/bin/kexec",  "-e", NULL))
		{
			fprintf(stderr, "Unable to exec kexec");
			perror(" ");
		}
	}*/
	system("kexec -e");
}

