#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <stdbool.h>
#include "config.h"
#include "moroz.h"

void MRZ_CFILE(const char *filename) {
    int fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0644);

    if (fd != -1) {
        close(fd);
    } else {
        fprintf(stderr, TXT_RED "ERROR !\n" TXT_RESET);
    }
}

void MRZ_CDIR(const char *dirname) {
    if (mkdir(dirname, 0755) != 0) {
        fprintf(stderr, TXT_RED "ERROR !\n" TXT_RESET);
    }
}

char *MRZ_RFILE(const char *path, const char *tag) {
    FILE *file = fopen(path, "r");
    if (!file) return NULL;

    char line[128];
    char key[64], val[64];
    static char result[64];
    result[0] = '\0';

    while (fgets(line, sizeof(line), file)) {
        if (sscanf(line, "%63s = %63s", key, val) == 2) {
            if (strcmp(key, tag) == 0) {
                strncpy(result, val, sizeof(result) - 1);
                result[sizeof(result) - 1] = '\0';
                fclose(file);
                return result;
            }
        }
    }

    fclose(file);
    return NULL;
}

void MRZ_PFILE(const char *path, const char *pline, long offset) {
    FILE *ffile = fopen(path, "r+");
    if (!ffile) {
        fprintf(stderr, TXT_RED "ERROR !\n" TXT_RESET);
        return; 
    }

    if (offset < 0) {
        fseek(ffile, 0, SEEK_END);
    } else {
        fseek(ffile, offset, SEEK_SET);
    }

    fprintf(ffile, "%s\n", pline);

    fflush(ffile);
    fsync(fileno(ffile));

    fclose(ffile);
}
