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

 int need_cache_update(char *urls_name,char *cache_name)
{
  char etmp[ML_ETMP];
  struct stat url_time;
  time_t cache_time;
  FILE *fp;
	
  // Urls file exist?
  if (access(urls_name,F_OK))  
   {
    #ifdef DEBUG_MAKE_CACHE
    fprintf(stderr," urls file not found, update not needed\n");
    #endif		    
    return(0);
   }

   // Cache file exist?
   if (access(cache_name,F_OK))
   {
    #ifdef DEBUG_MAKE_CACHE
     fprintf(stderr," cache file not found, need update\n");
    #endif		    
    return(1);
   }
   
  // Get curent modify time for urls
    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_MAKE_CACHE
     fprintf(stderr," Cache alredy exist, check modify time...\n");
     fprintf (stderr," urls file modify time: %s",ctime(&url_time.st_mtime));
    #endif		    	      
	    
    // Get modify time stored in cache file
      // Open file
    if ((fp=fopen(cache_name,"rb"))==NULL)
      { // Open error
       sprintf(etmp,"MAKE-CACHE: ERROR: Can't open file %s (for read),skip: %s\n",cache_name,strerror(errno));
       err_mes(etmp);
       exit(-1);
      }
      
      // Read data
    if (fread(&cache_time,1,sizeof(time_t),fp)<1)
      { // Read error
        sprintf(etmp,"MAKE-CACHE: ERROR: Can't read from file %s: %s,skip\n",cache_name,strerror(errno));
	err_mes(etmp);
	exit(-1);
      }
       fclose(fp);					       		        

    #ifdef DEBUG_MAKE_CACHE
    fprintf (stderr," stored in cache mtime: %s\n",ctime(&cache_time));
    #endif		    	      
	       
    if (cache_time==url_time.st_mtime)
        {
         #ifdef DEBUG_MAKE_CACHE
         fprintf(stderr," Cache file alredy exist and actual: use cache\n");
         #endif		   
	 return(0); 
	}
	
        #ifdef DEBUG_MAKE_CACHE
        fprintf(stderr," Modify time of urls file changed, rebuild cache\n");
        #endif

    return(1);
}

