#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 "manhat-lib/shared_util.h"
#include "manhat-lib/shared_delete.h"
#include "manhat-lib/shared_super_util.h"
#include "manhat-lib/shared_update_user_info.h"
#include "manhat-lib/shared_file_util.h"
#include "manhat-lib/shared_escape_realname.h"
#include "manhat-lib/shared_cs_util.h"


static
void read_parameters (char *key, char *course, char *username, char *realname, int *verified)
{
  char tmp[20];
  char temp_realname[MAX_NAME + 1];
      

  cs_get_required_parameter ("id", key, MAX_KEY);
  cs_get_required_parameter ("crs", course, MAX_PATH );
  cs_get_required_parameter ("username", username, MAX_USERNAME);
  
  cs_get_required_parameter ("realname", temp_realname, MAX_NAME);  
  unescape_realname(realname, temp_realname);    /* shared_escape_realname.c */

  cs_get_optional_parameter ("verify",tmp,19);
  *verified = atoi(tmp);

}




void
report_success (char *realname,  char *username, int deleted,  char *crs, const char *key)
{
   cs_set_value("realname", realname);
   cs_set_value("username", username);
   cs_set_int_value("deleted", deleted);  
   cs_set_value("crs", crs);  
   cs_set_int_value("success", 1);  
}


static 
void show_verification_page(const char *key,  char *course,  char *username,  char *realname)
{
   cs_set_value("realname", realname);
   cs_set_value("username", username);
   cs_set_value("crs", course);
}







int
main ()
{
  char key[MAX_KEY + 1];
  char username[MAX_USERNAME + 1];
  char realname[MAX_NAME + 1];
  char course[MAX_PATH + 1];	
  int verified;
  int deleted;			/* was the user's directory removed? */
  char dirname[MAX_PATH + 1];
  CONFIG_STRUCT conf;
  SESSION user;

  cs_cgi_init();
  read_parameters (key, course, username, realname, &verified);
  validate_super_key (key, &user);				/* shared_super_util.c */

  if(!verified)
     show_verification_page(key, course, username, realname);
  else
   {
    read_configuration_file (course, &conf);			/* shared_util.c */


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

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

    report_success (realname, username, deleted, course, key);
  }  
  cs_cgi_display("super_delete_student", 1);
  cs_cgi_destroy(); 
  return 0;
}

