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

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

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

static void
read_parameters (char *course, char *key, int *oper, char *user)
{
  char temp[30];

  cs_get_required_parameter ("crs", course, MAX_PATH);
  cs_set_value("crs", course);
  cs_get_required_parameter ("id", key, MAX_KEY);
  cs_set_value("id", key);
  cs_get_optional_parameter ("oper", temp, 29);
  if(strlen(temp))
    *oper =1;
  else
    *oper =0;
  if(*oper)
     cs_get_required_parameter ("student", user, 99);
}



void
set_common_data(const char *course, const char *key, CONFIG_STRUCT *conf)
{
  char url[MAX_PATH +1];

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

}




static void
set_data (const char *course, const char *key,
           CONFIG_STRUCT *conf)
{
  P_NODE *pers_head;
  set_common_data(course, key, conf);
  pers_head = build_option_person_list (conf);	/* shared_person_list.c */

  set_option_userlist (pers_head);	/* shared_person_list.c */
  free_option_person_list (pers_head);	/* shared_person_list.c */


}



void
set_user_data(USER_DATA *data, const char *course, const char *key, CONFIG_STRUCT *conf)
{
  set_common_data(course, key, conf);
  cs_set_value("username", data->username);
  cs_set_value("realname", data->realname);
  cs_set_value("user_id", data->id);
  cs_set_int_value("group", data->group);
  cs_set_int_value("display", 1);
}



int
main ()
{
  char course[MAX_PATH + 1];	/* from crs=? command line */
  char key[MAX_KEY + 1];	/* from id=? command line */
  char reset_user[100];	/* from id=? command line */
  SESSION user;
  CONFIG_STRUCT conf;
  int oper =0;
  USER_DATA data;

  cs_cgi_init();

  if(!ALLOW_PASSWORD_RESET)
       cs_critical_error(ERR_REQUEST_DENIED, "");

  read_parameters (course, key, &oper, reset_user);
  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 && is_wnec_faculty(user.id)) || (user.group == ADMIN))
   {
      if(!oper)
         set_data(course, key, &conf);
      else
      {
	 get_user_data (reset_user, &data, &conf);   /*shared_person_list.c */
         set_user_data(&data, course, key, &conf);
      }
     
   }
  else
    access_denied_error();  /*shared_access.c */
    
  cs_cgi_display("admin_reset_pass_form", 1);
  cs_cgi_destroy();
  return 0;

}

