#include <stdio.h>
#include <string.h>
#include <time.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include "global.h"
#include "custom.h"

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


#define MAX_LINE 300



void
read_parameters (char *key)
{
   cs_get_required_parameter ("id", key, MAX_KEY);
}



void get_file_time_string(const char *filename, char *timestring)
{
    char filepath[MAX_PATH +1];
    struct stat buff;

    snprintf(filepath, MAX_PATH +1, "%s/%s", AUTO_UPDATE_ROSTER_PATH, filename);

    if(stat(filepath, &buff))
	 *timestring = '\0';
    else
    {
       strftime(timestring, MAX_TIMESTRING, DOW_DATE_TIME_FORMAT, localtime(&(buff.st_ctime)));
    }

}



void  set_auto_files(const char *path_name, const char *prefix) 
{
   DIR *dir_p;
   struct dirent *dir_entry;
   char  timestring[MAX_TIMESTRING +1];
   char  name[MAX_PATH +1];
   int i =0;
   char *filename =0;


   filename = hdf_get_value(global_cgi->hdf, "Query.uploadfile", "");


   dir_p = opendir(path_name);
   if(!dir_p)
	return;

  while (NULL != (dir_entry = readdir(dir_p)))
  {
	if(strstr(dir_entry->d_name, ".xml"))
	{
	   snprintf(name, MAX_PATH +1, "%s.%d.name", prefix, i);
	   cs_set_value(name, dir_entry->d_name);
	   if(strcmp(dir_entry->d_name, filename) ==0)
	   {
	      snprintf(name, MAX_PATH +1, "%s.%d.new", prefix, i);
	      cs_set_int_value(name, 1);

	   }
           get_file_time_string(dir_entry->d_name, timestring);
	   snprintf(name, MAX_PATH +1, "%s.%d.timestring", prefix, i);
	   cs_set_value(name, timestring);
	   i++; 
	}
  }
  closedir(dir_p);

}


        
      


int
main()
{
  char key[MAX_KEY +1];
  char path[MAX_PATH +1];
  SESSION user;
  
  cs_cgi_init();
  read_parameters( key);
  validate_super_key(key, &user);

  set_admin_page(&user, key, 0, "super_new_course_form"); /* shared_super_page.c */
  
  snprintf(path, MAX_PATH +1, "%s", AUTO_UPDATE_ROSTER_PATH);
  set_auto_files(path, "roster_file"); 
  snprintf(path, MAX_PATH +1, "%s", AUTO_UPDATE_REQUEST_PATH);
  set_auto_files(path, "request_file"); 

  cs_cgi_display("super_auto_update_form", 1);
  cs_cgi_destroy();
  return 0;
}
