/* 3000menu.c */
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>

char *menu[] = {
        "/usr/bin/ls",
        "/usr/bin/ps",
        "/usr/bin/nano",
        "/usr/bin/top",
        "CUSTOM",
        "QUIT",
        NULL
};
        
int quit = 5;
const int CUSTOM = 4;

void run_program(int choice)
{
        int result;
        
        printf("Running %s\n", menu[choice]);
        
        result = system(menu[choice]);

        if (result != 0) {
                printf("Command failed.\n");
        } else {
                printf("Command succeeded.\n");
        }
                
        return;
}

int choose_program(void)
{
        int i = 0;
        int choice;
        char *input = NULL;
        size_t result, n = 0;

        printf("\nChoose a program to run:\n\n");
        
        while (i <= quit) {
                printf("%d. %s\n", i + 1, menu[i]);
                i++;
        }

        printf("\nYour choice? ");

        result = getline(&input, &n, stdin);
        choice = atoi(input);
        free(input);

        if ((result > 0) && (choice > 0) && (choice <= i)) {
                return choice - 1;
        } else {
                return -1;
        }
}

int main()
{
        int program;
        char *c;

        c = getenv("MENUCMD");
        
        if (c) {
                menu[CUSTOM] = c;
        } else {
                menu[CUSTOM] = menu[quit];
                quit = CUSTOM;
        }

        while (1) {
                program = choose_program();

                if (program == quit) {
                        return 0;
                }
                
                if (program != -1) {
                        run_program(program);
                }
        }
}
