#include <stdio.h>
#include <time.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>		/* for unlink */
#include <sys/types.h>		/* for opendir() et. al. */
#include <dirent.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_cookie.h"


static void
read_parameters (char *course, char *key)
{
  cs_get_required_parameter ("crs", course, MAX_PATH);	/* shared_cgi_util.c */
  cs_get_required_parameter ("id", key, MAX_KEY);	/* shared_cgi_util.c */

}

void
show_exit_file (const char *exit_path)
{
  FILE *fp;
  char line[200];
  char name[200];
  int i =0;

  fp = fopen (exit_path, "r");
  if (fp)
    {
      while (fgets (line, 199, fp))
      {
	snprintf(name, 200, "line.%d", i);
	cs_set_value(name, line);
      }
      fclose(fp);	
    }
}


static void
delete_key (char *key, CONFIG_STRUCT *conf)
{
  char keypath[MAX_PATH + 1];
  char correct_key[MAX_KEY + 1];
  
  check_key_for_cookie(key, correct_key);   /* shared_util.c */
  snprintf (keypath, MAX_PATH + 1, "%skeys/%s", conf->course_path, correct_key);
  unlink (keypath);
}



static void
show_logout_screen(CONFIG_STRUCT *conf)
{
  char exit_path[MAX_PATH + 1];

  snprintf (exit_path, MAX_PATH + 1, "%s%s", conf->course_path, EXIT_FILE);
  cs_set_course_info(conf);
  cs_set_current_time(); 
  show_exit_file (exit_path);
  cs_set_int_value("standalone_logout", 1);
}




int
main (void)
{
  char course[MAX_PATH + 1];	/* from crs=? command line */
  char key[MAX_KEY + 1];	/* from id=? command line */
  SESSION user;
  CONFIG_STRUCT conf;		/* the configuration read from config file */


  cs_cgi_init();
  read_parameters (course, key);
  read_configuration_file (course, &conf);	/* shared_util.c */
  validate_key (key, &user, &conf);	/* shared_util.c */
  
  if(conf.standalone)
  {
     delete_key (key, &conf);
     remove_stale_symlinks (user.username, course, conf.access);  /* shared_news_util.c */
 
     if(COOKIES_ENABLED)   /* custom.h */
          set_cookie(COOKIE_DONE, ALIAS,"");   /* shared_cookie.c */
     show_logout_screen(&conf);
     cs_cgi_display("doorstep", 1);
  }
  else
      printf("Location: %s?id=%s\n\n", "mymanhattan", key);  
  cs_cgi_destroy();
  return 0;
}

