#include <stdio.h>
#include <time.h>


#include "global.h"

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

static void
read_parameters (char *course, char *key, long *offset, int *topic, char *score_path)
{
  char astring[80];


  cs_get_required_parameter ("crs", course, MAX_PATH);	/* shared_cgi_util.c */
  cs_get_required_parameter ("id", key, MAX_KEY);	/* shared_cgi_util.c */

  cs_get_required_parameter ("loc", astring, 79);	/* shared_cgi_util.c */
  *offset = atol (astring);

  cs_get_required_parameter ("topic", astring, 79);	/* shared_cgi_util.c */
  *topic = atoi (astring);

  cs_get_required_parameter("path",score_path, MAX_PATH);   /* shared_cgi_util.c */
  
}


int
main (void)
{
  char course[MAX_PATH + 1];	/* from crs=? command line */
  char key[MAX_KEY + 1];	/* from id=? command line */
  long offset;			/* from loc=? command line */
  int topic;                    /* from topic=? command line */
  char score_path[MAX_PATH + 1];   /* from path=? command line */

  SESSION user;
  CONFIG_STRUCT conf;		/* the configuration read from config file */

  FILE *fp;
  int fd;
  time_t no_time = 0;
 
  cs_cgi_init(); 

  read_parameters (course, key, &offset, &topic, score_path);

  read_configuration_file (course, &conf);	/* shared_util.c */
  validate_key (key, &user, &conf);	/* shared_util.c */
  if(!has_write_permission(&user, &conf))   /* shared_access.c */
      access_denied_error();



  if(user.group != FACULTY)
         cs_critical_error (ERR_REQUEST_DENIED, "");

  fp = fopen(score_path,"r+");
  if(!fp)
     cs_critical_error(ERR_FOPEN_READ_FAILED,"");
  fd = fileno(fp);
  get_exclusive_lock(fd,1);  /* shared_lock.c */
  
  if(fwrite(&no_time, sizeof(time_t), 1, fp) != 1)
     cs_critical_error(ERR_FWRITE_FAILED, "");
     
  release_lock(fd);  /* shared_lock.c */
  fclose(fp);
  
  printf("Location: %s?crs=%s&id=%s&loc=%ld&topic=%d\n\n",  "assign_fac_expand", course, key, offset, topic);
  cs_cgi_destroy();
  return 0;
}

