/*
    REFERENCES -- bibliographic software
    Copyright (C) 1995-2007  Volker Kiefel

    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 <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <time.h>

#include "refs.h"
#include "interf.h"
#include "rglobal.h"
#include "fl_ut.h"
#include "initial.h"
#include "mmenu.h"
#include "str_fun.h"
#include "interf.h"

 extern FILE * dir_kat;

static int ok_datei_groesse(const char * d_name, int ds_groesse);
int datenbank_untersuchen(void);
void refs_aufraeumen(void);

int refsrun_name_darf_geloescht_werden;


int main(int argc, char * argv[])
{
  FILE * fprefsrun;

 
  signal(SIGINT,SIG_IGN);
  /* initialize global variables, including pathnames */
  atexit(refs_aufraeumen); 
  refsrun_name_darf_geloescht_werden = 1;
  initialisieren();
  cfg_datei_lesen();
  weiter_initialisieren(); 

  if (isfile(refsrun_name))
  {
     static char ein[INPUT_BU_LEN+1];
     int option;
     
     refsrun_name_darf_geloescht_werden = 0;
     wrtxt("\n(Warning: one copy of `References' still running\n"
              "  or previous session terminated irregularly)\n");
     anhalten();
     wrtxt("\n  For more information, please read the ``Error messages and warnings'' chapter");
     wrtxt("\n  in the documentation: ``Problems with refsrun.$''\n");
     anhalten();
     
     wrtxt("\nStart or stop References [start/q]\n");
     strcpy(ein,"menu");
     option = menu_wahl(ein,
       "[start] no other instance of References running with current database\n"
       "[    q] quit, do not start References with the current database"
       );
     if (option==2)
     {
       exit(1);
     } else
     {
       refsrun_name_darf_geloescht_werden = 1;
     }
  }
  if ((fprefsrun=fopen(refsrun_name,"w"))==NULL)
  {
    fprintf(stderr,"\n(Problem: Cannot create %s)\n",refsrun_name);
    exit(1);
  }
  fprintf(fprefsrun,"One copy of References %s running",REFS_VERSION);
  fclose(fprefsrun);
  
  /* 
   * (the initialization in `weiter_initialisieren' requires 
   * that cfg_datei_lesen() has been executed) 
   */
  if (!datenbank_untersuchen())
  {
     wrtxt("\n\nAt least one database file damaged\n");
     anhalten();
     exit(1);
  }
  else
  {
     wrtxt("\n");
  }
  /* dateien_und_pfade_anzeigen(); */ 
  if (argc > 1)
  {
     if (!strcmp(argv[1],"-h") || !strcmp(argv[1],"--help"))
     {
        wrtxt("\n"
              "-h --help             print this help screen\n"
              "-v --version          print version and compilation time"
              "\n");
        return 0;
     }
     if (!strcmp(argv[1],"-v") || !strcmp(argv[1],"--version"))
     {
        sprintf(wrtxtbu,"\nReferences v%s, compiled %s, %s\n",
          REFS_SUB_VERSION,__DATE__,__TIME__);
        wrtxt(wrtxtbu);
        return 0;
     }
    
  }
  {
    time_t zeit;
    time(&zeit);
    sprintf(wrtxtbu,"REFERENCES opened: %s",ctime(&zeit));
    protokollieren(wrtxtbu);
  }
  refsmenu();
  {
    time_t zeit;
    time(&zeit);
    sprintf(wrtxtbu,"REFERENCES closed: %s",ctime(&zeit));
    protokollieren(wrtxtbu);
  }
  return 0;
}

int datenbank_untersuchen(void)
{
/* Namen fuer file check */
   char bbt_pfad[PFAD_LEN+1];
   int n_dateien, j;
   char suchmuster[PFAD_LEN + 1];

   int rgwert;

   rgwert = 1;
   wrtxt("\n(Checking size of database files)");

   if (ok_datei_groesse(journal_name,sizeof(journal_rec))==0) rgwert=0;
   if (ok_datei_groesse(journal_pix_name,sizeof(refspix_rec))==0) rgwert=0;
   if (ok_datei_groesse(desc_name,sizeof(desc_rec))==0) rgwert=0;
   if (ok_datei_groesse(book_name,sizeof(buch_rec))==0) rgwert=0;
   if (ok_datei_groesse(autorjl_name,sizeof(author_rec))==0) rgwert=0;
   if (ok_datei_groesse(autorbu_name,sizeof(author_rec))==0) rgwert=0;
   if (ok_datei_groesse(quell_name,sizeof(quell_rec))==0) rgwert=0;
   if (ok_datei_groesse(quell_pix_name,sizeof(quellpix_rec))==0) rgwert=0;
   if (ok_datei_groesse(stichw_name,sizeof(keylist_rec))==0) rgwert=0;
   if (ok_datei_groesse(stichw_pix_name,sizeof(keylistpix_rec))==0) rgwert=0;
   if (ok_datei_groesse(abstr_dat_name,sizeof(abstr_rec))==0) rgwert=0;
   if (ok_datei_groesse(abstr_pix_name,sizeof(abstrpix_rec))==0) rgwert=0;
   if (ok_datei_groesse(formdef_name,sizeof(formdef_rec))==0) rgwert=0;

   strlimcpy(suchmuster,rdbpfad,PFAD_LEN);
   strlimcat(suchmuster,"*.bbt",PFAD_LEN);
   /* wrtxt("(ok)\n(bbt)"); */
   wrtxt("\n(Checking size of bbt-files)");
   // n_dateien =  verzeichnis_auslesen(suchmuster);
   n_dateien =  verzeichnis_auslesen(rdbpfad,"*.bbt");
   if (n_dateien > 0)
   {
      char zeile[PFAD_LEN+1];
      dir_kat_lesen();
      for (j=1;j<=n_dateien;j++)
      {
        int schleife_beenden;

        schleife_beenden = 0;
        if(fgets(zeile,PFAD_LEN-1,dir_kat)==NULL)
        {
          fprintf(stderr,"\nUnexpected error: Reading of directory-catalog\n");
          exit(1);
        }
        rtrim(zeile,'\n');
        strlimcpy(bbt_pfad,rdbpfad,PFAD_LEN);
        strlimcat(bbt_pfad,zeile,PFAD_LEN);
        if (ok_datei_groesse(bbt_pfad,sizeof(bbatchtable_rec))==0)
        {
                     rgwert=0;
        }

      }
      dir_kat_schliessen();
      dir_kat_loeschen();
   }
   return rgwert;
}

static int ok_datei_groesse(const char * d_name, int ds_groesse)
{
   int ok;
   long f_groesse;

   ok = 1;
   f_groesse = filesize((char *) d_name);
   if (f_groesse > 0)
   {
      if (f_groesse % ds_groesse != 0)
      {
         ok = 0;
      }
      /* else
      {
         wrtxt(".");
      }
      */
   }
   return ok;
}


void refs_aufraeumen(void)
{
   if (isfile(refsrun_name) && (refsrun_name_darf_geloescht_werden==1))
   {
      remove(refsrun_name);
      wrtxt("\n(References closed)\n");
#ifdef REFS_USES_LINUXGCC
      wrtxt("\n");
#endif
   }
}
