#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "global.h"

#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_super_util.h"
#include "manhat-lib/shared_cs_util.h"
#include "manhat-lib/shared_news_util.h"






static void
write_xml_cgi_file (FILE *infp, const char *username, char *orig_fname)
{

#define CHUNKSIZE 2048
  FILE  *outfp;
  int bytes_read;
  int bytes_left;
  char buffer[CHUNKSIZE];
  char filepath[MAX_PATH + 1];
  struct stat file_stat;
  char *is_auto =0;
  char *filename =0;


  is_auto = hdf_get_value(global_cgi->hdf, "Query.auto", "");
  if(is_auto && strlen(is_auto))
  {
    filename = hdf_get_value(global_cgi->hdf, "Query.file", "");
    if(strlen(filename) == 0)
	 cs_critical_error(ERR_PARAM_MISSING, "write cgi file");

    snprintf (filepath, MAX_PATH + 1, "%s", AUTO_UPDATE_ROSTER_PATH);
    mkdir(filepath,0777);
    get_orig_fname (filename, orig_fname);  /* shared_news_util.c */

    snprintf (filepath, MAX_PATH + 1, "%s/%s", AUTO_UPDATE_ROSTER_PATH, orig_fname);
  }
  else
    snprintf (filepath, MAX_PATH + 1, XML_ROSTER_PATH, username);

  if(fstat(fileno(infp), &file_stat))
      cs_critical_error(ERR_NO_FILE, "");
  if(file_stat.st_size ==0)
      cs_critical_error(ERR_NO_FILE, "");

  outfp = fopen (filepath, "w");
  if (!outfp)
    cs_critical_error (ERR_FOPEN_WRITE_FAILED, filepath);


  bytes_left = file_stat.st_size;
 
  bytes_read = CHUNKSIZE;
  while (bytes_left)
    {
      if (bytes_left < CHUNKSIZE)
	bytes_read = bytes_left;
      if (fread (buffer, bytes_read, 1, infp) != 1)
	cs_critical_error (ERR_FREAD_FAILED, "");
      bytes_left -= bytes_read;
      if (fwrite (buffer, bytes_read, 1, outfp) != 1)
	cs_critical_error (ERR_FWRITE_FAILED, filepath);

    }
  fclose (outfp);
#undef CHUNKSIZE

}


 
 


        
int main()
{
  char key[MAX_KEY + 1];
  SESSION user;
  FILE *fp =0;
  char *is_auto =0; 
  char *filename =0;
  char orig_fname[MAX_PATH +1]; 

  cs_cgi_init();
  cs_get_required_parameter ("id", key, MAX_KEY );   /* get the key */
  validate_super_key(key, &user);   /* shared_super_util.c */
  fp = cgi_filehandle (global_cgi, "file");
  if(!fp)
    cs_critical_error(ERR_UPLOAD_FILE, "");
  write_xml_cgi_file (fp, user.username, orig_fname);
  is_auto = hdf_get_value(global_cgi->hdf, "Query.auto", "");
  filename = hdf_get_value(global_cgi->hdf, "Query.file", "");
  if(strlen(is_auto))
    printf("Location: %s?id=%s&uploadfile=%s\n\n", "super_auto_update_form", key, orig_fname);
  else
    printf("Location: %s?id=%s\n\n", "super_upload_xml_roster_form", key);
  cs_cgi_destroy(); 
  return 0;
}


