/* aide, Advanced Intrusion Detection Environment
 *
 * Copyright (C) 1999 Rami Lehti
 *
 * 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 <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

#include "report.h"
#include "list.h"
#include "aide.h"
#include "be.h"

int cmp_url(url_t* url1,url_t* url2){
  
  return ((url1->type==url2->type)&&(strcmp(url1->value,url2->value)==0));
  
}

int error_init(url_t* url)
{
  list* r=NULL;
  FILE* fh=NULL;
  
  if(conf->verbose_level>=200){
    error(5,"WARNING: Debug output enabled\n");
  }

  for(r=conf->report_url;r;r=r->next){
    
    if (cmp_url((url_t*)r->data,url)) {
      
      error(5,"WARNING: Already have report output %s\n",url->value);
      return RETOK;
    }
    
  }
  
  fh=be_init(0,url);
  if(fh!=NULL) {
    conf->report_fd=list_append(conf->report_fd,(void*)fh);
    conf->report_url=list_append(conf->report_url,(void*)url);
    return RETOK;
  }
  
  error(0,"Cannot open %s for writing\n",url->value);

  return RETFAIL;

}

void error(int errorlevel,char* error_msg,...)
{
  va_list ap;
  int retval=0;
  list* r=NULL;

  if(conf->verbose_level==-1){
    if(5<errorlevel){
      return;
    }
  }else{ 
    if(conf->verbose_level<errorlevel){
      return;
    }
  }

  if(conf->report_fd==NULL){
    /* We haven't initialized yet so let's use the default */
    va_start(ap, error_msg);
    vfprintf(stdout,error_msg,ap);
    va_end(ap);
    return;
  }

  for(r=conf->report_fd;r;r=r->next){
    va_start(ap, error_msg);
    retval=vfprintf((FILE*)r->data, error_msg,ap);
    va_end(ap);
    if(retval==0){
      va_start(ap, error_msg);
      retval=vfprintf((FILE*)r->data, error_msg,ap);
      va_end(ap);
      if(retval==0){
	exit(ERROR_WRITING_ERROR);
      }
    } 
  }

  return;
}
