/* mr_file.c
 *
 * $Id$
 *
 * File management for mondo
 * Code (c)2006 Bruno Cornec <bruno@mondorescue.org>
 *   
 * Provided under the GPLv2
 */


#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>

#include "mr_err.h"
#include "mr_msg.h"

/*open and read file: each call must be coupled with mr_conf_close
  function: return 0 if success*/
FILE *mr_fopen_int(const char *path, const char *mode,int line, char *file) {
	FILE *fd = NULL;

	if ((fd = fopen(path, mode)) == NULL) {
		mr_msg_int(1,line,file,"mr_fopen_int","Unable to open %s",path);
		mr_exit(-1,"Exiting");
	}
	return(fd);
}

void mr_fprintf_int(FILE *fd, int line, char *file, const char *fmt, ...) {
	
	va_list args;

	if (fd == NULL) {
		mr_msg_int(1,line,file,"mr_fprintf_int","fd is NULL.\nShould NOT happen.");
		mr_exit(-1,"Exiting");
	}
	va_start(args,fmt);
	if (vfprintf(fd, fmt, args) < 0) {
		mr_msg_int(1,line,file,"mr_fprintf_int","Unable to print to fd");
		mr_exit(-1,"Exiting");
	}
	va_end(args);
}

void mr_fclose_int(FILE **fd, int line, char *file) {

	if (fd == NULL) {
		mr_msg_int(1,line,file,"mr_fclose_int","fd is NULL.\nShould NOT happen.");
		mr_exit(-1,"Exiting");
	}
	if (*fd == NULL) {
		mr_msg_int(1,line,file,"mr_fclose_int","File descriptor is NULL.\nShould NOT happen.");
		mr_exit(-1,"Exiting");
	}
	if (fclose(*fd) < 0) {
		mr_msg_int(1,line,file,"mr_fclose_int","Unable to close File Descriptor");
	}
	*fd = NULL;
}

void mr_mkdir_int(const char *pathname, mode_t mode, int line, char *file) {

	if (mkdir(pathname,mode) != 0) {
		mr_msg_int(1,line,file,"mr_mkdir_int","Unable to create directory %s",pathname);
		mr_exit(-1,"Exiting");
	}
}

/* Version of getcwd using dynamically allocated memory. Cf: man 3p getcwd */
char *mr_getcwd_int(int line, char *file) {

long path_max;
size_t size;
char *buf;
char *ptr;

path_max = pathconf(".", _PC_PATH_MAX);
if (path_max == -1) {
	size = (size_t)512;
} else if (path_max > 10240) {
	size = (size_t)10240;
} else {
	size = (size_t)path_max;
}

for (buf = ptr = NULL; ptr == NULL; size *= 2) {
	if ((buf = realloc(buf, size)) == NULL) {
		mr_msg_int(1,line,file,"mr_getcwd","Unable to realloc memory");
		mr_exit(-1,"Exiting");
	}

	ptr = getcwd(buf, size);
	if (ptr == NULL && errno != ERANGE) {
		mr_msg_int(1,line,file,"mr_getcwd","Unable to get current working directory");
		mr_exit(-1,"Exiting");
	}
return(buf);
}
}
