/* 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 "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,"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,"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,"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,"fd is NULL.\nShould NOT happen.");
		mr_exit(-1,"Exiting");
	}
	if (*fd == NULL) {
		mr_msg_int(1,line,file,"File descriptor is NULL.\nShould NOT happen.");
		mr_exit(-1,"Exiting");
	}
	if (fclose(*fd) < 0) {
		mr_msg_int(1,line,file,"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,"Unable to create directory %s",pathname);
		mr_exit(-1,"Exiting");
	}
}
