/* Copyright (c) 2018, 2020, 2022 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/stdlib/mkostemps.c
 * Create a temporary file. (called from C89)
 */

#define arc4random_buf __arc4random_buf
#define open __open
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

static const char* letters =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

int __mkostemps(char* template, int suffixLength, int flags) {
    size_t length = strlen(template);
    if (length < (size_t) suffixLength + 6) {
        errno = EINVAL;
        return -1;
    }

    char* xtemplate = template + length - suffixLength - 6;
    if (strncmp(xtemplate, "XXXXXX", 6) != 0) {
        errno = EINVAL;
        return -1;
    }

    do {
        uint64_t value;
        arc4random_buf(&value, sizeof(value));
        for (size_t i = 0; i < 6; i++) {
            xtemplate[i] = letters[value % 64];
            value /= 64;
        }

        int fd = open(template, O_RDWR | O_CREAT | O_EXCL | flags, 0600);
        if (fd >= 0) return fd;
    } while (errno == EEXIST);

    return -1;
}
__weak_alias(__mkostemps, mkostemps);
