#include <stdio.h>
#include <string.h>
#include <unistd.h>		/* unlink(), rmdir() ... */
#include <sys/types.h>
#include <dirent.h>		/* Directory information.       */
#include <sys/stat.h>		/* for stat() */

#include "global.h"
#include "custom.h"

#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_delete.h"
#include "manhat-lib/shared_cs_util.h"
#include "manhat-lib/shared_update_user_info.h"
#include "manhat-lib/shared_access.h"

void
read_parameters (char *course, char *key, char *username, char *realname)
{
  char value[10];
  char student[100];
  char *ptr;


  cs_get_required_parameter ("crs", course, MAX_PATH);
  cs_get_required_parameter ("id", key, MAX_KEY);
  cs_get_required_parameter("student", student, 99); 

  ptr = strchr (student, ':');
  if (!ptr)
    cs_critical_error (ERR_PARAM_MISSING, "");
  *ptr = '\0';
  if(strlen(student) ==0 )
    cs_critical_error (ERR_PARAM_MISSING, "");
  strncpy (username, student, MAX_USERNAME);
  if(strlen(ptr+1) == 0)
    cs_critical_error (ERR_PARAM_MISSING, "");
  strncpy (realname, ptr + 1, MAX_NAME);
  cs_get_required_parameter("validate", value, 9); 
  cs_get_required_parameter("validate2", value, 9); 
  
}





int
main ()
{

  char username[MAX_USERNAME + 1];	/* derived from 'student' field */
  char realname[MAX_NAME + 1];	/* derived from 'student' field */
  char course[MAX_PATH + 1];	/* from crs=? command line */
  char key[MAX_KEY + 1];	/* from id=? command line */
  int deleted;			/* was the user's directory removed? */
  char dirname[MAX_PATH + 1];
  char url[MAX_PATH + 1];
  SESSION user;
  CONFIG_STRUCT conf;

  cs_cgi_init();  

  read_parameters (course, key, username, realname);
  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 */

  
  if ( (user.group != FACULTY) && (user.group != ADMIN))
    cs_critical_error (ERR_REQUEST_DENIED, "");

  if(!conf.standalone)
    delete_course(username, course);    /* delete course in central course list file - shared_delete.c */

  mark_passwd_file (username, &conf);
  deleted = !user_contributed (username, &conf);  /* shared_delete.c */
  if (deleted)
    {
      snprintf (dirname, MAX_PATH + 1, "%s%s/%s",
		conf.course_path, PEOPLE_DIR, username);
      remove_directory (dirname);
    }
  cs_set_int_value("deleted", deleted);
  cs_set_course_info(&conf);
  cs_set_current_time();

  snprintf(url, MAX_PATH +1, "%s?id=%s&amp;crs=%s", "admin_main_menu", key, course);
  cs_set_value("back_url", url);

   #ifdef HIDE_MANHATTAN_USERNAMES
   cs_set_int_value("hide_manhattan_username", 1);
  #endif

  cs_set_value("username", username);
  cs_set_value("realname", realname);
  cs_set_int_value("display_deleted", 1);
  cs_cgi_display("admin_del_student_form", 1);
  cs_cgi_destroy(); 
  
  return 0;
}

