#include <stdio.h>
#include <string.h>
#include <sys/stat.h>		/* for stat() */

#include "global.h"

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


static void
read_parameters (char *course, char *key, 
		 int *grp, int *topic, int *parent, char *folder_name)
{
  char string[80];
  

  cs_get_required_parameter ("crs", course, MAX_PATH);

  cs_get_required_parameter ("id", key, MAX_KEY);

  cs_get_required_parameter ("grp", string, 79);
  *grp = atoi (string);

  cs_get_required_parameter ("topic", string, 79);
  *topic = atoi (string);

  cs_get_required_parameter("parent", string, 79);
  *parent = atoi(string);

  cs_get_required_parameter("folder_name", folder_name, MAX_SUBJECT);
  strtrm(folder_name);
  
  if(!*folder_name)
     cs_critical_error(ERR_GENERAL_ERROR, "folder name is empty");
      
}










static void
complete_send (int grp,  SESSION *user,  time_t time_sent,
	          int parent, int topic, 
	          const char *folder_name)
{
  FILE  *inbox_fp;
  int  inbox_fd;
  struct stat buf;
  
  char inbox_fname[MAX_PATH + 1];
  int msg_id;
  CENTRAL_INBOX_RECORD inbox_record, new_inbox_record;
  int inbox_record_size;
  
 /* memorize the sizes of these data structure, 
 ** so we don't have to repeatedly call sizeof()
 */
  inbox_record_size = sizeof(CENTRAL_INBOX_RECORD); 
  



  /* set up as much of the new inbox record as we can before locking
  ** the inbox.dat file
  */  
  *new_inbox_record.info.msg_fname = '\0';  /* folders have a blank msg_fname */

  strncpy(new_inbox_record.info.sender, user->username, MAX_USERNAME + 1);
  strncpy(new_inbox_record.info.sender_realname, user->realname, MAX_NAME + 1);
  *new_inbox_record.info.receiver_username = '\0';
  strncpy(new_inbox_record.info.subject, folder_name, MAX_SUBJECT + 1);
  new_inbox_record.info.time_sent = time_sent;
  new_inbox_record.info.attachments = 0;
  new_inbox_record.info.sender_team = user->team;
  new_inbox_record.info.reply_to = parent;
  

  *new_inbox_record.info_fname = '\0';   /* folders don't use an info file */
  
  new_inbox_record.release_time = 0;       /* no release time set */
  new_inbox_record.unrelease_time = 0;     /* no unrelease time either */
  new_inbox_record.status =  NORMAL;   
  
  /* now open and lock the inbox.dat file */
  snprintf(inbox_fname,MAX_PATH + 1,"%s%s",central_discussion_path,INBOX_FNAME);
 
  inbox_fp = fopen(inbox_fname,"a+");
  if(!inbox_fp)                              /* couldn't open or create inbox.dat */
    cs_critical_error(ERR_FOPEN_WRITE_FAILED,"");
  inbox_fd = fileno(inbox_fp);
  get_exclusive_lock(inbox_fd, 1);                      /* shared_lock.c */
  
  
  /* get the next available msg_id, by incrementing the msg_id of the
  ** last msg in the inbox.dat file
  */
  fstat(inbox_fd, &buf);
  if(!buf.st_size)    /* this is the first message */
     msg_id = 1;
  else
    {
     if(fseek(inbox_fp,-inbox_record_size,SEEK_END) == -1)
       cs_critical_error(ERR_FSEEK_FAILED, inbox_fname);
     if(fread( &inbox_record, inbox_record_size, 1, inbox_fp) != 1)
       cs_critical_error(ERR_FREAD_FAILED, inbox_fname);
     msg_id =  inbox_record.info.msg_id + 1;
    }
    
    
   new_inbox_record.info.msg_id = msg_id;
   new_inbox_record.info.topic_id = topic == -1? msg_id : topic;
   if(fseek(inbox_fp,0,SEEK_END) == -1)
     cs_critical_error(ERR_FSEEK_FAILED, inbox_fname);

   if(fwrite(&new_inbox_record, inbox_record_size,1,inbox_fp) != 1)
      cs_critical_error(ERR_FWRITE_FAILED, inbox_fname);



   release_lock(inbox_fd);     /* shared_lock.c */
   fclose(inbox_fp);
   
// NOT NEEDED FOR A FOLDER?????   write_user_inbox_record(msg_id, time_sent);    /* shared_news_util.c */
}





int
main (void)
{
  char course[MAX_PATH + 1];	/* from crs=? command line */
  char key[MAX_KEY + 1];	/* from id=? command line */
  int grp;			/* from grp=? command line */
  int topic;			/* from topic=? command line */
  int parent;                 /* from parent=? command line */

  char folder_name[MAX_SUBJECT + 1];  /* from folder_name = command line */


  
  SESSION user;
  CONFIG_STRUCT conf;	
  time_t time_sent;
  

  cs_cgi_init();      /* shared_cs_util.c */
  read_parameters (course, key, &grp, &topic, &parent,  folder_name);

  
  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();                /* shared_access.c */
  
  /* only FACULTY can create folders, and in modules that support it
  */
  if((user.group != FACULTY) || !group_uses_folders(grp))   /* shared_news_util.c */
      cs_critical_error(ERR_REQUEST_DENIED, "");
  
  time_sent = time (NULL);   /* this is the timestamp of when this msg was sent */

  set_discussion_names (conf.course_path, user.username, grp);	/* shared_news_util.c */

  if(!create_dirs_between(discussion_path))    /* shared_file_util.c */
      cs_critical_error(ERR_MKDIR_FAILED, discussion_path);
  if(!create_dirs_between(central_discussion_path))
      cs_critical_error(ERR_MKDIR_FAILED, discussion_path);

  
  /* send the message */
  complete_send(grp, &user, time_sent,  parent, topic, folder_name);



  printf("Location: news_topic?crs=%s&id=%s&grp=%d#%d\n\n", course,key,grp,topic);

  cs_cgi_destroy();
  return 0;
}




