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

/*
     __
___( o)>
\ <_. )
 `---'
 Coic Coic
 */



char** split(char* line){

    if(!line) return NULL;

    int index = 0;
    //int words = 0;
    int capa_words = 5;
    char *token;
    
    // 5 car generalement les commandes ne vont pas plus loin
    // 4 args + le NULL
    // mmmh maybe pour gcc, les rm, touch, mkdir mais azy on fait un realloc à ce moment flemme de compter tous les mots
    
    char **tokens = malloc(capa_words * sizeof(char *));
    if(!tokens) exit(1);

    index = 0;
    token = strtok(line, " \n\t");
    
    while(token != NULL){
    
        tokens[index] = token;
        index ++;

        if(index >= capa_words) {
            capa_words += 5;
            tokens = realloc(tokens, capa_words * sizeof(char *));
            if(!tokens){
                free(tokens); 
                exit(1);
            }

        }

        token = strtok(NULL, " \n\t");

    } 
    if(!tokens) return NULL;
    tokens[index] = NULL;
    return tokens;
}

int exec_cmd(char** args){

    if(!args || !*args) return -1;
    
    int wstatus;
    pid_t pid = fork();

    if (pid < 0) exit(-1);
    // Child
    else if (pid == 0){

        if(strcmp(args[0] , "run") != 0) exit(-1);
        
        if(execvp(args[1], args + 1) != 0) exit(-1);
        exit(0);
    
        //if(execvp(args[0], args) == -1) exit(-1);
        //exit(0);
    }

    //Uncle... You're again ! Oh it's not my uncle it's my daddy !
    //Can you tell to my ACDC to decode my README ? It will be fun !
    //In the next README I will put a 14Mo picture inside encoded in b64 :)
    
    else{

        if(waitpid(pid, &wstatus, 0) ==  -1) return -1; 
        
        if( WIFEXITED(wstatus)){
            if(WEXITSTATUS(wstatus) == 255) return -1;
            else return WEXITSTATUS(wstatus);
    }}
    return 0;
}

int execution_loop(){
    
    // Vars
    
    //Dernier code de sortie 
    int last_code = 0;
    
    char buffer[2048]; //reset -> buffer[0] = '\0'
    
    // Les args de commande 
    char **args;
    while (1){ //boucle inf
    
        fputs("> ", stdout); //invitation à entrer une coooooooommmmmaaaaaaaannnnndde
        
        // on recupere le texte tapé grace a stdin
        fgets(buffer, 2047, stdin);
        
        //on split les args {arg1, arg2, arg3}
        // arg1 -> commande (run, exit, ?)
        // arg2 -> pour run la commande voulue et un code d'exit pour exit 
        args = split(buffer);
        
        //on compte les args 
        int index = 0;
        while(args[index] != NULL) index ++;
        
       // printf("nbr args : %i\n", index);

        if (index > 0){ // si l'user rentre juste un ' ' ou rien

            if (strcmp(args[0], "exit") == 0 ){
                 
                if (args[1]) last_code = atoi(args[1]);
                
                else last_code = 0;
                    
                free(args);
                return last_code;        
            }
            
            //execution du run <commande> via le child 
            else if (strcmp(args[0], "run") == 0){
                //printf("test\n");
                if(args[1]) last_code = exec_cmd(args);
            }
            
            //interrogation du last_code 
            else if (strcmp(args[0], "?") == 0){
                
                printf("%i\n", last_code);
            }
            
            else {
                    printf("Unknown command\n");
            }
        }
        free(args); // on ne peux pas malloc 2 fois args
        buffer[0] = '\0'; // on reset le buffer
    }
    return 0;
}

int is_terminal()
{
    return isatty(STDIN_FILENO) && isatty(STDOUT_FILENO);
}
/*
int main() {
  printf("\n Code de fin : %i\n",execution_loop());
}
*/

/*
int main(){
    char* cmd1[] = {"ls", "-l", NULL};
    int res = exec_cmd(cmd1);
// res = 0
// execute ls -l and return the exit code
    printf("%i\n",res);
}*/

/*
int main(){

char input[] = "run ls -l  -h   ";
char** res = split(input);
// res[0] = "run"
// res[1] = "ls"
// res[2] = "-l"
// res[3] = "-h"
// res[4] = NULL
int index = 0;
while(res[index] != NULL){

    printf("res[%d] = \"%s\"\n", index, res[index]);
    index ++;
}
free(res);
}*/
