#include <stdio.h>
#include <stdlib.h>  /* for exit */
#include <time.h>
#include <dirent.h>
#include <string.h>

#include <sys/stat.h>
#include <unistd.h>


#include "global.h"
#include "custom.h"		/* for date FORMAT strings */


#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_super_util.h"
#include "manhat-lib/shared_authenticate.h"
#include "manhat-lib/shared_time.h"
#include "manhat-lib/shared_cs_util.h"
#include "manhat-lib/shared_super_menu.h"

void
clean_dir(const char *dir,  int cleaning_tmp_dir , const char *dirname)
{
 #define MAX_TMP_NAME 40
	DIR *dir_p;
	struct dirent *dir_entry;
	struct stat buf;
	char fname[MAX_PATH +1];
	time_t now;
	long bytes_deleted = 0;
	int files_deleted = 0, i=0;
	char timestring[MAX_TIMESTRING+1];
	char name[MAX_TMP_NAME];


        now = time(NULL);
	dir_p = opendir(dir);
	if(!dir_p)
          cs_critical_error(ERR_OPENDIR_FAILED, "");
	while((dir_entry=readdir(dir_p)) != NULL)
	{
	   /** CGI_DATA is the old prefix used for uploaded file (pre 3.0)
	   *** The Clearsilver CGI kit uses cgi_upload as a prefix
	   **/
       	   if(cleaning_tmp_dir ? ((strstr(dir_entry->d_name, "CGI_DATA_")== dir_entry->d_name) ||
       	              (strstr(dir_entry->d_name, "cgi_upload")== dir_entry->d_name) ||              
       	              !strcmp(dir_entry->d_name,CHAT_MSG_LOG)) 
                                       : *dir_entry->d_name != '.' )
	   {
		snprintf(fname, MAX_PATH +1, "%s/%s", dir, dir_entry->d_name);
		if(cleaning_tmp_dir? stat (fname, &buf) : lstat(fname,&buf))  /* since if this is not the tmp dir, we're looking at symbolic links */  
		 {
		     unlink(fname);   /* can't stat file - try to delete it */
		 }
                else	
		 if((now - buf.st_mtime) > MAX_KEY_EXPIRE)
		  {
		   files_deleted++;
		   bytes_deleted += buf.st_size;
		   strftime(timestring, MAX_TIMESTRING, DOW_DATE_TIME_FORMAT,
			localtime(&buf.st_mtime));
		   snprintf(name, MAX_TMP_NAME, "%s.file.%d.filename", dirname, i);
		   cs_set_value(name, dir_entry->d_name);
		   snprintf(name, MAX_TMP_NAME, "%s.file.%d.time", dirname, i);
		   cs_set_value(name, timestring);
		   snprintf(name, MAX_TMP_NAME, "%s.file.%d.size", dirname, i);
		   cs_set_int_value(name, (long)buf.st_size);
		   unlink(fname);
		   i++;
		 }
	   }		
	}
	closedir(dir_p);
        snprintf(name, MAX_TMP_NAME, "%s.files_deleted", dirname);
        cs_set_int_value(name, files_deleted);
        snprintf(name, MAX_TMP_NAME, "%s.bytes_deleted", dirname);
        cs_set_int_value(name, bytes_deleted);
 #undef MAX_TMP_NAME
}

int person_clipboard_expired(char *dir, char *timestring)
{
   char path[MAX_PATH +1];
   struct stat buf;
   time_t now;

   snprintf(path, MAX_PATH +1, "%s/%s", dir, CLIPBOARD_INF_FNAME);
   if(stat(path, &buf))
   {
     *timestring = '\0';
     return 1;
   }
   
   now = time(NULL);
   if((now - buf.st_mtime) > MAX_CLIPBOARD_EXPIRE)
   {
     strftime(timestring, MAX_TIMESTRING, DOW_DATE_TIME_FORMAT,
			localtime(&buf.st_mtime));
      return 1;
    }
   else
     return 0; 
}


void
clean_clipboard()
{
 #define MAX_TMP_NAME 40
   char path[MAX_PATH +1];
   char dir[MAX_PATH +1];
   DIR *dir_p;
   struct dirent *dir_entry;
   int number_visited_dirs = 0;
   int number_processed_dirs = 0;
   char name[MAX_TMP_NAME];
   char timestring[MAX_TIMESTRING+1];
   int expired = 0;

   snprintf(path, MAX_PATH +1, "%s", CLIPBOARD_PATH);

   dir_p = opendir(path);
   if(!dir_p)
       cs_critical_error(ERR_OPENDIR_FAILED, "clean_clipboard");

   while((dir_entry=readdir(dir_p)) != NULL)
   {
     
    if( *dir_entry->d_name != '.' )
    {
     snprintf(dir, MAX_PATH +1, "%s%s", path, dir_entry->d_name);
     expired = person_clipboard_expired(dir, timestring);
     if(expired)
     {
         kill_directory(dir);  /* shared_file_util.c */
	 snprintf(name, MAX_TMP_NAME, "clipboard.%d.userid", number_processed_dirs);
         cs_set_value(name, dir_entry->d_name);
         if(strlen(timestring))
         {
	    snprintf(name, MAX_TMP_NAME, "clipboard.%d.createdtime", number_processed_dirs);
            cs_set_value(name, timestring);
         }
         
       number_processed_dirs++;
     } 
     number_visited_dirs++;
    }	
   }
   cs_set_int_value("number_visited_dirs", number_visited_dirs);
   cs_set_int_value("number_processed_dirs", number_processed_dirs);
 #undef MAX_TMP_NAME
}


void
clean_up()
{
	char dir[MAX_PATH +1];

	snprintf(dir, MAX_PATH +1, TMP_PATH);
        clean_dir(dir, 1, "tmp");
	snprintf(dir, MAX_PATH +1, "../images/links");
        clean_dir(dir, 0, "image");
        clean_clipboard();
	cs_set_current_time();
}
			    
			
			





int
main ()
{

	char key[MAX_KEY + 1];
	SESSION user;
        
	cs_cgi_init();
        read_param( key);
        validate_super_key(key, &user);
	set_admin_page(&user, key, 0, "super_clean");  /* shared_super_menu.c */
        clean_up();
        cs_cgi_display("super_clean", 1);
	cs_cgi_destroy();
        return 0;
}

