#include <stdio.h>
#include <stdlib.h>		/* for atol() */
#include <time.h>
#include <string.h>
#include <ctype.h>

#include "global.h"


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


static void
read_parameters (char *course, char *key, long *offset, time_t * day)
{
  char temp[50];


  cs_get_required_parameter ("crs", course, MAX_PATH);	/* shared_cgi_util.c */
  cs_get_required_parameter ("id", key, MAX_KEY);
  cs_get_required_parameter ("loc", temp, 49);
  *offset = atol (temp);

  cs_get_required_parameter ("day", temp, 49);
  *day = (time_t) atol (temp);


}


/* writes a '1' to the 'deleted' value of the record starting at
** 'offset'.  Should implement file locking.  What happens if the
** chat server writes to the file at the same time?
*/

void
delete_item (long offset, CONFIG_STRUCT *conf)
{
  char path[MAX_PATH + 1];
  int deleted = 1;
  FILE *fp;

  snprintf (path, MAX_PATH + 1, "%s/%s", conf->course_path, CHAT_MSG_LOG);
  fp = fopen (path, "r+");
  if (!fp)
    cs_critical_error (ERR_FOPEN_READ_FAILED, path);

  if (fseek (fp, offset + sizeof (time_t), SEEK_SET))	/* records starts at offset, but we need to also skip the msg_time */
    cs_critical_error (ERR_FSEEK_FAILED, path);
    
  fwrite (&deleted, sizeof (int), 1, fp);
  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 */
  time_t day;			/* from day=? command line */
  SESSION user;
CONFIG_STRUCT conf;		/* the configuration read from config file */

  cs_cgi_init();

  read_parameters (course, key, &offset, &day);
  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, "");

  delete_item (offset, &conf);

  printf ("Location: %s?crs=%s&id=%s&day=%ld\n\n", "chat_transcript", course,
	  key, (long)day);

  cs_cgi_destroy();
  return 0;
}

