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

#include "global.h"

#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_cs_util.h"
#include "manhat-lib/shared_person_list.h"
#include "manhat-lib/shared_access.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);
  cs_set_value("crs", course);
  cs_set_value("id", key);
}


static void
set_student_data( P_NODE *person)
{
#define MAX_TMP_NAME 30
  char name[MAX_TMP_NAME];
  int i =0;
  P_NODE *ptr;

  for(ptr = person; ptr; ptr = ptr->next)
  {
     if(ptr->data.group != FACULTY)
     {
	  snprintf(name, MAX_TMP_NAME, "std.%d.username", i);
          cs_set_value(name, ptr->data.username);
	  snprintf(name, MAX_TMP_NAME, "std.%d.realname", i);
          cs_set_value(name, ptr->data.realname);
	  snprintf(name, MAX_TMP_NAME, "std.%d.id", i);
          cs_set_value(name, ptr->data.id);
       i++;
     }
  }
#undef MAX_TMP_NAME 
}

static void
set_data (const char *course, const char *key, CONFIG_STRUCT *conf,  SESSION * user)
{
  
  P_NODE *person;
  char url[MAX_PATH +1];
   

  person =  build_option_person_list (conf);                      /* shared_person_list.c */
  cs_set_course_info(conf);   /* shared_cs_util.c */
  cs_set_current_time();

  /* adjust list so 1) a teacher cannot delete himself  and
  ** 2) an ADMIN running this program can't delete the only teacher
  **/
  person = faculty_adjusted_option_list(person, user);  /* shared_person_list.c */
  
  snprintf (url, MAX_PATH +1, "%s?crs=%s&amp;id=%s","admin_main_menu", course, key);
  cs_set_value("back_url", url);

  set_option_userlist (person);       /* shared_person_list.c */

  /* quickly delete students from the class and this is only for Manhattan administrators */
  if(user->group == ADMIN)           
        set_student_data( person);
  
  free_option_person_list (person);	/* shared_person_list.c */

}



int
main ()
{
  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(!has_write_permission(&user, &conf))   /* shared_access.c */
     access_denied_error();                 /* shared_access.c */

  if ((user.group == FACULTY) || (user.group == ADMIN))
    set_data (course, key, &conf, &user);
  else
    cs_critical_error(ERR_REQUEST_DENIED, "");

  cs_cgi_display("admin_del_student_form", 1);
  cs_cgi_destroy();
  return 0;			/* exit successfully */

}



