/*
 * Created by hongbo.he@lnxall.com
 *
 * 2025/09/01
 */
#ifndef LNXUTILS_FOP_H
#define LNXUTILS_FOP_H

#include <unistd.h>

/*
 * read file and map its content to memory-buffer
 *
 * RETURN VALUE
 *	if success, return 0
 *	when error occurrd, return -1 and you can find the cause from errno
 *
 */
int lnxutil_read_map(const char *path, char **pout, size_t *len);

void lnxutil_read_unmap(int fd, char *pout, size_t len);

/*
 * read file content to buffer user indicated
 *
 * RETURN VALUE
 *	if success, return bytes actual read
 *	when error occurrd, return -1 and you can find the cause from errno
 *
 */
int lnxutil_read_to_buffer(const char *path, char *outbuf, size_t len);

int lnxutil_read_file_alloc(const char *path, char **pout);

/*
 * write data to file (not append)
 *
 * RETURN VALUE
 *	if success, return bytes actual written
 *	when error occurrd, return -1 and you can find the cause from errno
 *
 */
int lnxutil_write_file(const char *path, const char *data, size_t len);

/*
 * write data into file excludely and non-block
 *  `lnxutil_write_file_atomic_retry' will retry up to 7 times,
 *		with a delay of approximately 5 seconds totally
 *
 * RETURN VALUE
 *	if success, return bytes actual written
 *	or return -1 and set the errno
 *
 * ERRORS
 *  EWOULDBLOCK
 *		indicating the file is locked
 *
 */
int lnxutil_write_file_atomic(const char *path, const char *data, size_t len);

int lnxutil_write_file_atomic_retry(const char *path, const char *data, size_t len);

/*
 * caculate md5 value of file
 *
 * RETURN VALUE
 *	if success, return 0
 *	or return -1 to indicate an error and set the errno
 *
 */
int lnxutil_md5sum(const char *path, char *outbuf, size_t len);

/*
 * check if the md5sum of file equals to md5sum indicates
 *
 * RETURN VALUE
 *	return an integer less than, equal to, or greater than zero
 *		if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2
 */
int lnxutil_check_md5sum_file(const char *path, const char *md5sum);

/*
 * extract name from file path
 *
 * RETURN VALUE
 *	if success, return 0
 *	when error occurrd, return -1
 *
 */
int lnxutil_get_filename(const char *path, char *outbuf, size_t len);

/*
 * get resource from url, store to local file
 *
 * RETURN VALUE
 *	if success, return 0
 *	in all another case, return -1 and you can find the cause from errno
 *
 */
int lnxutil_wget(const char *url, const char *path, int timeout);

/*
 * mkdir -p path
 * rm -r -f path:
 *	DIFF:
 *	1. if argument is `.` or `..`, the directory self will be also remove
 *		such as /dir_a - this_program: execute `lnxutil_rmdir_r(".")
 *		               - dir_c
 *		        the the whole /dir_a will be remove, include itself
 *	2. no permition to remove "/"
 *
 * RETURN VALUE
 *  if success or directory already exists, return 0
 *  else return -1 and set the errno
 *
 */
int lnxutil_mkdir_p(const char *path);
int lnxutil_rmdir_r(const char *path);

#endif
