/*
 * OpenComal -- a free Comal implementation
 *
 * This file is part of the OpenComal package.
 * (c) Copyright 1992-2024 Jos Visser <josvisser66@gmail.com>
 *
 * The OpenComal package is covered by the GNU General Public
 * License. See doc/LICENSE for more information.
 */

/* OpenComal SYS routine implementations for Posix operating systems */

#include "pdcglob.h"
#include "pdcexec.h"
#include "pdccmd.h"

#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>

PUBLIC void sys_rand(long *result, long *scale) {
    *result = rand();
    *scale = RAND_MAX;
}

PUBLIC void *sys_alloc(long size) {
    if (size > MAXUNSIGNED)
        return NULL;

    return calloc(1, (unsigned) size);
}


PUBLIC void *sys_realloc(void *block, long newsize) {
    if (newsize > MAXUNSIGNED)
        return NULL;

    return realloc(block, (unsigned) newsize);
}


PUBLIC void sys_free(void *p) {
    free(p);
}

PUBLIC char *sys_dir_string() {
    int buf_size = 256;
    char *buf = 0;

    while (1 == 1) {
        if (!buf) buf = (char *) malloc(buf_size);

        if (getcwd(buf, buf_size) != NULL) return buf;

        if (errno == ERANGE) { /* buffer too small */
            buf_size += 256;
            free(buf);
            buf = 0;
        } else
            run_error(DIRS_ERR, strerror(errno));
    }
}

PUBLIC char *sys_unit_string() {
    return strdup("C:"); /* :-) */
}

PUBLIC void sys_unit(char *unit) {
}

PUBLIC void sys_chdir(char *dir) {
    if (chdir(dir) < 0)
        run_error(DIR_ERR, strerror(errno));
}

PUBLIC void sys_mkdir(char *dir) {
    if (mkdir(dir, 0777) < 0)
        run_error(DIR_ERR, strerror(errno));
}

PUBLIC void sys_rmdir(char *dir) {
    if (rmdir(dir) < 0)
        run_error(DIR_ERR, strerror(errno));
}

PUBLIC void sys_opencomalrc() {
    const char *homedir = getenv("HOME");

    if (!homedir)
        return;

    char filename[PATH_MAX];

    strcpy(filename, homedir);
    strcat(filename, "/.opencomalrc");

    if (access(filename, F_OK) == 0)
        do_enter(filename);
}


