/*
 *  Copyright 1994-2022 Olivier Girondel
 *
 *  This file is part of lebiniou.
 *
 *  lebiniou is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  lebiniou is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with lebiniou. If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef __BINIOU_UTILS_H
#define __BINIOU_UTILS_H

#if HAVE_CONFIG_H
#include "config.h"
#include "includes.h"
#else
#error "No config.h"
#endif

#if __STDC_VERSION__ < 199901L
#if __GNUC__ >= 2
#define __func__ __FUNCTION__
#else
#define __func__ "<unknown>"
#endif
#endif
#include "jansson.h"

#define DIRECTORY_MODE S_IRWXU|S_IRWXG|S_IRWXO


void xdebug(const char *, ...);
void xerror(const char *, ...);
void xperror(const char *);
#define xprout() xerror("*prout* (_!_) at %s:%d (%s)\n", __FILE__, __LINE__, __func__);
void okdone(const char *);
void *xmalloc(const size_t);
void *xcalloc(const size_t, const size_t);
void *xrealloc(void *, size_t);
#define xfree(ptr) do { free(ptr); ptr = NULL; } while (0)

double xatof(const char *);
long xstrtol(const char *);
uint64_t xstrtoull(const char *);

uint32_t FNV_hash(const char*);
void ms_sleep(const uint32_t);
int parse_two_shorts(const char *, const int, short *, short *);

extern uint8_t       libbiniou_verbose;
#define VERBOSE(X) if (libbiniou_verbose) { X; fflush(stdout); }

int check_command(const char *);

time_t unix_timestamp(void);

int is_equal(const char *, const char *);

#ifdef DEBUG
#define DEBUG_JSON(name, json, pretty) {                                \
    int flags = JSON_SORT_KEYS|JSON_ENCODE_ANY;                         \
    flags |= pretty ? JSON_INDENT(2) : JSON_COMPACT;                    \
    char *tmp = json_dumps(json, flags);                                \
    fprintf(stderr, "JSON [%s:%d %s]\n", __FILE__, __LINE__, __func__); \
    fprintf(stderr, "JSON %s:\nJSON %s\n\n", name, tmp);                \
    xfree(tmp);                                                         \
  }
#else
#define DEBUG_JSON(name, json, pretty)
#endif

uint8_t safe_filename(const char *);

json_t *json_strtok(const char *, const char *);

char *get_desktop_dir(void);
int8_t create_dirs(void);
uint8_t has_desktop_symlink(void);

#endif /* __BINIOU_UTILS_H */
