#include <errno.h>
#include <fcntl.h>
#include <luna.h>
#include <stdlib.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>

extern "C"
{
    int execv(const char* program, char* const[])
    {
        return (int)syscall(SYS_exec, program);
    }

    int execve(const char*, char* const[], char* const[])
    {
        NOT_IMPLEMENTED("execve");
    }
    int execvp(const char*, char* const[])
    {
        NOT_IMPLEMENTED("execvp");
    }

    pid_t fork(void)
    {
        return syscall(SYS_fork);
    }

    pid_t getpid(void)
    {
        return getprocid(ID_PID);
    }

    pid_t getppid(void)
    {
        return getprocid(ID_PPID);
    }

    unsigned int sleep(unsigned int seconds)
    {
        return msleep(seconds * 1000);
    }

    ssize_t read(int fd, void* buf, size_t count)
    {
        return syscall(SYS_read, fd, count, buf); // yes, our read() syscall is in the wrong order.
    }

    ssize_t write(int fd, const void* buf, size_t count)
    {
        return syscall(SYS_write, fd, count, buf); // yes, our write() syscall is in the wrong order.
    }

    int close(int fd)
    {
        return (int)syscall(SYS_close, fd);
    }

    off_t lseek(int fd, off_t offset, int whence)
    {
        return syscall(SYS_seek, fd, offset, whence);
    }

    __lc_noreturn void _exit(int status)
    {
        syscall(SYS_exit, status);
        __lc_unreachable();
    }

    int dup(int fd)
    {
        return fcntl(fd, F_DUPFD, 0);
    }

    int access(const char* path, int amode)
    {
        return (int)syscall(SYS_access, path, amode);
    }

    int isatty(int fd)
    {
        int result = fcntl(fd, F_ISTTY);
        if (result < 0) return 0;
        return 1;
    }

    char* getcwd(char* buf, size_t size)
    {
        const char* dummy_cwd = "/"; // FIXME: Actually retrieve the current working directory from the kernel.
        if (size < 2)
        {
            errno = ERANGE;
            return NULL;
        }
        if (!buf) { buf = (char*)malloc(size); }
        strlcpy(buf, dummy_cwd, 2);
        return buf;
    }
}