#include <stdio.h>
#include <string.h>
#include <ctype.h>		/* for isdigit() */
#include <dirent.h>

#include "global.h"
#include "grade.h"


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



static void
read_parameters (char *course, char *key)
{
    cs_get_required_parameter("crs", course, MAX_PATH);
    cs_get_required_parameter("id", key, MAX_KEY);
}


static void
send_tab_file (char *crs, CONFIG_STRUCT *conf, SESSION *user)
{
  FILE *fp;
  char ch;
  long filesize;
  char source_fname[MAX_PATH + 1];
  char dest_fname[MAX_PATH + 1];
  char modified_course[MAX_PATH + 1];
  char *cptr;
  
  snprintf (source_fname, MAX_PATH + 1, "%s%s/%s",
	    conf->course_path, "grade_book", GRADES_TAB_FNAME);
  
  
  /* course contains a slash / separating the directories
  ** first, we convert the slash to a dot . 
  */
  course_slash_to_dot(crs, modified_course);   /* shared_util.c */
  
    /* MS IE does a weird thing with an attachment that has two dots.
  ** It appears to put a [1] before the first dot.  For example, if
  ** told that the attachment is called "c102.ac10101.txt", IE will
  ** want to save the file as "c102[1].ac10101.txt".  To circumvent this,
  ** we'll replace the first dot with an underscore
  */
  cptr = strchr(modified_course, '.');
  if(cptr)
     *cptr = '_';


  
  snprintf (dest_fname, MAX_PATH + 1, "%s_grades.txt", modified_course);
  fp = fopen (source_fname, "r");
  if (!fp)
    cs_critical_error (ERR_NO_RELEASED_GRADES, "");

  fseek (fp, 0, SEEK_END);
  filesize = ftell (fp);
  fseek (fp, 0, SEEK_SET);

  printf ("Content-type:application/octet-stream\n");
  printf ("Content-disposition:attachment; filename=\"%s\"\n", dest_fname);
  printf ("Content-length: %ld\n\n", filesize);
  while (fread (&ch, 1, 1, fp) == 1)
    fwrite (&ch, 1, 1, stdout);
  fclose (fp);
}






int
main (void)
{
  char course[MAX_PATH + 1];	/* from crs=? command line */
  char key[MAX_KEY + 1];	/* from id=? command line */
  SESSION user;
  CONFIG_STRUCT conf;
  
  cs_cgi_init();           /* shared_cs_util.c */
  read_parameters (course, key);
  read_configuration_file (course, &conf);	/* shared_util.c */
  validate_key (key, &user, &conf);	/* shared_util.c */

  if (user.group != FACULTY)
    cs_critical_error (ERR_REQUEST_DENIED, "");
  send_tab_file (course, &conf, &user);
  cs_cgi_destroy();      /* shared_cs_util.c */
  return 0;
}

