#include <stdio.h>
#include <unistd.h>
#include <string.h>

#include "global.h"

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


char *
read_parameters (char *course, char *key,
		 int *grp, char *from, char *dirname)
{

  char astring[25];
  char *temp;
  char *fname;


  cs_get_required_parameter ("crs", course, MAX_FILENAME);
  cs_get_required_parameter ("id", key, MAX_KEY);

  cs_get_required_parameter ("grp", astring, 5);
  *grp = atoi (astring);

  cs_get_required_parameter ("from", from, MAX_FROM);
  cs_get_required_parameter ("dir", dirname, MAX_FILENAME);

  temp = hdf_get_value(global_cgi->hdf, "Query.fname", 0);
  if(!temp || !strlen(temp)) 
     cs_critical_error(ERR_PARAM_MISSING, "fname");
  fname = (char *)malloc(sizeof(char)*strlen(temp) +1);
  if(!fname)
     cs_critical_error(ERR_MALLOC_FAILED, "");
  strncpy(fname, temp, strlen(temp) +1);
  return fname;
}





static void
create_symlink (const char *crs, const char *dirname, const char *fname)
{
  char *dirpath;
  dirpath = (char *)malloc(sizeof(char)*(strlen(crs) + strlen(dirname) + strlen(fname)+ strlen(discussion_path)+1));
  
  if(!dirpath)
     cs_critical_error(ERR_MALLOC_FAILED, "");

  snprintf (dirpath, MAX_PATH + 1, "%s%s", discussion_path, dirname);
  if (chdir (dirpath))
    cs_critical_error (ERR_CHDIR_FAILED, "");
  unlink (ZIP_START_FNAME);	/* in case it's there */

  if (symlink (fname, ZIP_START_FNAME))
    cs_critical_error (ERR_SYMLINK_FAILED, "");
  if(dirpath)
     free(dirpath);
}

static void
back_up (char *program)
{
  char temp[MAX_PATH + 1];

  translate_url_substitutes (temp, program, MAX_PATH + 1, 0);	/* shared_translate_url.h */
  printf ("Location: %s\n\n", temp);
}





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

  cs_cgi_init();
  fname = read_parameters (course, key, &grp, from, dirname);
  read_configuration_file (course, &conf);	/* shared_util.c */
  validate_key (key, &user, &conf);	/* shared_util.c */

  set_discussion_names (conf.course_path, user.username, grp);	/* shared_news_util.c */
  create_symlink (course, dirname, fname);

  back_up (from);
  if(fname)
    free(fname);
  cs_cgi_destroy();
  return 0;
}

