/* Copyright (c) 2021 Dennis Wölfing
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/* libc/src/unistd/execlp.c
 * Execute a program.
 */

#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>

int execlp(const char* path, const char* argv0, ...) {
    int argc = 1;
    va_list ap;
    va_start(ap, argv0);
    while (va_arg(ap, char*)) {
        argc++;
    }
    va_end(ap);

    char** argv = malloc((argc + 1) * sizeof(char*));
    if (!argv) return -1;

    va_start(ap, argv0);
    argv[0] = (char*) argv0;
    for (int i = 1; i < argc; i++) {
        argv[i] = va_arg(ap, char*);
    }
    argv[argc] = NULL;
    va_end(ap);

    execvp(path, argv);

    free(argv);
    return -1;
}
