// log.cc - implements logging class, log_file.
//    Copyright (C) 2000, 2001 Laurynas Biveinis <lauras@softhome.net>
//
//    This program 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.
//
//    This program 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 this program; if not, write to the Free Software
//    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//

#include "global.h"
#include "log.h"

#include <sys/stat.h>
#include <dir.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

log_file::log_file(const char * log_fn)
{
   char         new_name[FILENAME_MAX + 1];
   int          log_num = 1; // Numeric suffix for creation of new names
   char         tail[4];
   struct ffblk file_info;

   // If log_fn is an empty string, assume default
   strcpy(new_name, log_fn[0] ? log_fn : default_log_name);
   
   // A nice-for-SFN way to make up available file name - overwriting
   // file extension with .1, .2, and so on, until free name is found

   int not_found = findfirst(new_name, &file_info, FA_ARCH | FA_RDONLY);
   
   if (!not_found)
   {
      // Lets create backups only for regular files.  If we have something
      // else, like /dev/null, just use it.
      struct stat stat_buf;
      if (stat(new_name, &stat_buf) < 0)
      {
 	 if (errno == ENOENT)
	    not_found = 1;
	 /* TODO: FIXME: Fail properly if errno != ENOENT */
	 else
	    not_found = 1;
      }
      else if (!S_ISREG(stat_buf.st_mode))
      {
         not_found = 1;
      }
   }
   
   while (!not_found && (log_num <= 999))
   {
      itoa(log_num++, tail, 10);
      strcpy(strrchr(new_name, '.'), log_fn);
      not_found = findfirst(new_name, &file_info, FA_ARCH | FA_RDONLY);
   }
   log_stream = new std::ofstream(new_name);
}

log_file::~log_file(void)
{
   delete log_stream;
}

void log_file::print_log(const char * fmt, ...) const
//     __attribute__((format (printf, 2, 3)))
{
   char print_buf[256];
   va_list args;
   va_start(args, fmt);
   vsprintf(print_buf, fmt, args);
   va_end(args);
   (*log_stream) << print_buf << '\n';
}
