// Atari ST save-file + disk-space HAL.
//
// SAVES/ is a real GEMDOS subdirectory next to the .PRG, made with POSIX
// mkdir; delete is stdio remove(); free space comes from GEMDOS Dfree on the
// default drive.

#include <stdio.h>
#include <sys/stat.h>

#include <mint/osbind.h>
#include <mint/ostruct.h>

#include "joey/file.h"
#include "port.h"


#define SAVE_DIR_MODE   0777
#define ST_MAX_U32      0xFFFFFFFFu


uint32_t jlpDiskFree(void) {
    _DISKINFO  info;
    uint32_t   bytesPerClus;

    // Dfree drive 0 = the current (default) GEMDOS drive; < 0 is an error.
    if (Dfree(&info, 0) < 0) {
        return 0u;
    }
    // Saturate in 32-bit (no 64-bit multiply helper on the 68000).
    bytesPerClus = (uint32_t)info.b_secsiz * (uint32_t)info.b_clsiz;
    if (bytesPerClus != 0u && (uint32_t)info.b_free > ST_MAX_U32 / bytesPerClus) {
        return ST_MAX_U32;
    }
    return (uint32_t)info.b_free * bytesPerClus;
}


bool jlpSaveDelete(const char *path) {
    return remove(path) == 0;
}


bool jlpSaveDirEnsure(const char *dir) {
    struct stat  st;

    if (mkdir(dir, SAVE_DIR_MODE) == 0) {
        return true;
    }
    return stat(dir, &st) == 0 && S_ISDIR(st.st_mode);
}
