#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_news_util.h"
#include "manhat-lib/shared_translate_url.h"
#include "manhat-lib/shared_access.h"

static void
read_parameters (char *course, char *key, long *offset, char *from)
{
  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 ("from", from, MAX_FROM);	/* shared_cgi_util.c */
  
}



static void
release_msg(long offset)
{
 FILE *fp;
 int fd;
 char inbox_fname[MAX_PATH + 1];
 CENTRAL_INBOX_RECORD msg;

   snprintf(inbox_fname,MAX_PATH + 1,"%s%s",central_discussion_path,INBOX_FNAME);
   fp = fopen(inbox_fname, "r+");
   if(!fp)
       cs_critical_error(ERR_FOPEN_READ_FAILED, "");
   fd = fileno(fp);
   get_exclusive_lock(fd,1);  /* shared_lock.c */
 
   if(fseek(fp,offset,SEEK_SET))
       cs_critical_error(ERR_FSEEK_FAILED, "");
   if(fread(&msg, sizeof(CENTRAL_INBOX_RECORD), 1, fp) != 1)
       cs_critical_error(ERR_FREAD_FAILED, "");
   msg.status = NORMAL;

   if(fseek(fp,offset,SEEK_SET))
       cs_critical_error(ERR_FSEEK_FAILED, "");
   
   if(fwrite(&msg, sizeof(CENTRAL_INBOX_RECORD), 1, fp) != 1)
       cs_critical_error(ERR_FWRITE_FAILED, "");
    release_lock(fd);
    fclose(fp);
} 
 
  

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 */
  char from[MAX_FROM + 1];      /* from from=? command line */
  
  char translated_from[MAX_PATH + 1];
  
  SESSION user;
  CONFIG_STRUCT conf;		/* the configuration read from config file */

  cs_cgi_init();

  read_parameters (course, key, &offset, from);

  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, "");

  set_discussion_names (conf.course_path, user.username, ASSIGNMENTS);	/* shared_news_util.c */
  release_msg(offset);
  
  translate_url_substitutes (translated_from, from, MAX_PATH + 1,0);	/* shared_translate_url.c */  
  printf("Location: %s\n\n",  translated_from);
  
  cs_cgi_destroy(); 
  return 0;
}

