#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include "vars.h"

int write_cache(int section,char *urls_name,char *cache_name)
{
  char etmp[ML_ETMP];
  FILE *fp;
  int i;
  char **table;
  struct stat url_time;


  #ifdef DEBUG_WRITE_CACHE
  fprintf(stderr,"Write cache for %s from %s to file %s\n",redir[section]->name,urls_name,cache_name);
  #endif

  /*** Generate pointer table for cache ***/
 
  // Allocate memory
  table=(char **)malloc((1+redir[section]->ban_urls_count)*sizeof(char *));
    if (table==NULL)
       {
        err_mes("MAKE-CACHE: ERROR: Can't allocate memory\n");
        exit(-1);
       }
  // set first pointer to zero
  table[0]=0;
  
  // Set other pointer
  for (i=1;i<redir[section]->ban_urls_count;i++)
     table[i]=table[i-1]+(int)strlen(redir[section]->ban_urls[i-1])+1;

       
  // Open file
  if ((fp=fopen(cache_name,"wb"))==NULL)
     { // Open error
       sprintf(etmp,"MAKE-CACHE: ERROR: Can't open file %s (for write): %s\n",cache_name,strerror(errno));
       err_mes(etmp);
       exit(-1);
     }

   // Get urls file modify time
   if (stat(urls_name, &url_time)<0)
     { // Stat error
       sprintf(etmp,"MAKE-CACHE: ERROR: Can't stat file %s, skip: %s",urls_name,strerror(errno));
       err_mes(etmp);
       exit(-1);
      }
  #ifdef DEBUG_WRITE_CACHE
   fprintf (stderr," urls file modify time: %s\n",ctime(&url_time.st_mtime));
  #endif
  
    // Write modify time
    if (fwrite(&url_time.st_mtime,1,sizeof(time_t),fp)<1)
     { // Write error
       sprintf(etmp,"MAKE-CACHE: ERROR: Can't write to file %s: %s\n",cache_name,strerror(errno));
       err_mes(etmp);
       exit(-1);
     }

 // Write ban_urls_count
    if (fwrite(&redir[section]->ban_urls_count,1,sizeof(redir[section]->ban_urls_count),fp)<1)
     { // Write error
       sprintf(etmp,"MAKE-CACHE: ERROR: Can't write to file %s: %s\n",cache_name,strerror(errno));
       err_mes(etmp);
       exit(-1);
     }

 // Write pointers table
    if (redir[section]->ban_urls_count)
    if (fwrite(&table[0],redir[section]->ban_urls_count,sizeof(table[i]),fp)<1)
     { // Write error
       sprintf(etmp,"MAKE-CACHE: ERROR: Can't write to file %s: %s\n",cache_name,strerror(errno));
       err_mes(etmp);
       exit(-1);
     }

 #ifdef DEBUG_WRITE_CACHE
 // print pointer table
    for(i=0;i<redir[section]->ban_urls_count;i++)
     fprintf(stderr,"%i %p\n",i,table[i]);
 #endif


 // Write ban_urls data
  for (i=0; i<redir[section]->ban_urls_count; i++)
    if (fwrite(redir[section]->ban_urls[i],1,strlen(redir[section]->ban_urls[i])+1,fp)<1)
     { // Write error
       sprintf(etmp,"MAKE-CACHE: ERROR: Can't write to file %s: %s\n",cache_name,strerror(errno));
       err_mes(etmp);
       exit(-1);
     }
  fclose(fp);

  #ifdef DEBUG_WRITE_CACHE
   fprintf(stderr,"write %i elements to cache\n",redir[section]->ban_urls_count);
  #endif

return(0);
}

