#include <stdio.h>
#include <string.h>
#include "vars.h"

/***************************************
 ********** Start MAIN function ********/
 int main(int argc, char* argv[])
{
  int z;
  char cache_name[ML_FILE_NAME],urls_name[ML_FILE_NAME],etmp[ML_ETMP];

    // Load redirector.conf
    if (argc==1) get_opt(DEFAULT_CONFIG);
    else if (argc==2)  get_opt(argv[1]);


  // section cycle
    for (z=0;z<sections_count; z++)
       {
        if ((strlen(redir[z]->ban_dir)+15) >ML_FILE_NAME)
	  {
	    printf("\n MAKE-CACHE: ERROR: Very long path (>%i). Please, contact to developer\nExit..\n",ML_FILE_NAME);
	    err_mes("\n MAKE-CACHE: ERROR: Very long path. Please, contact to developer\nExit..\n");
	    exit(-1);
	  }
	
	 // urls file
         sprintf(cache_name,"%s/urls.cache",redir[z]->ban_dir);
	 sprintf(urls_name,"%s/urls",redir[z]->ban_dir);

        #ifdef DEBUG_MAKE_CACHE
         fprintf(stderr,"\n=== %s: %s > %s ===\n",redir[z]->name,urls_name,cache_name);
        #endif		    

	if (!need_cache_update(urls_name,cache_name))
	  continue;

        #ifdef DEBUG_MAKE_CACHE
	fprintf(stderr,"\nMAKE: %s > %s\n",urls_name,cache_name);
	#endif
	sprintf(etmp,"MAKE-CACHE: MAKE %s",cache_name);
	err_mes(etmp);
	
        
	    if(load_urls(z,urls_name)<0) continue;
	    if (redir[z]->ban_urls_count>0)  prune_urls(z);
	    write_cache(z,urls_name,cache_name);	    
       } // for z

  // Allow urls file
  if (allow_urls_file)
  {

    sprintf(cache_name,"%s/allow_urls.cache",redir[0]->ban_dir);
    sprintf(urls_name,"%s",allow_urls_file);

        #ifdef DEBUG_MAKE_CACHE
        fprintf(stderr,"\n=== urls_file: %s > %s ===\n",urls_name,cache_name);
        #endif		    

	if (!need_cache_update(urls_name,cache_name))
	  return(0);

        #ifdef DEBUG_MAKE_CACHE
	fprintf(stderr,"\nMAKE: %s > %s\n",urls_name,cache_name);
	#endif
	sprintf(etmp,"MAKE-CACHE: MAKE %s",cache_name);
	err_mes(etmp);
	
        
        if(load_urls(0,urls_name)<0) return(0);
        if (redir[0]->ban_urls_count>0)  prune_urls(0);
         write_cache(0,urls_name,cache_name);	    
  
  }
         
 return(0);
}

