#include <stdio.h>		/* standard io functions */
#include <string.h>
#include <ctype.h>
#include <unistd.h>		/* for unlink() */
#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_authenticate.h"
#include "manhat-lib/shared_central_user.h"
#include "manhat-lib/shared_super_util.h"
#include "manhat-lib/shared_encrypt.h"
#include "manhat-lib/shared_escape_realname.h"
#include "manhat-lib/shared_central_log.h"
#include "manhat-lib/shared_cs_util.h"

void
read_parameters ( char *key, char *username, char *id_number, 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 ("username", username, MAX_USERNAME);

  cs_get_required_parameter ("realname", temp_realname, MAX_NAME);
  unescape_realname(realname, temp_realname);   /* shared_escape_realname.c */

  cs_get_required_parameter ("id_number", id_number, MAX_ID);
  
  cs_get_optional_parameter("verify",tmp,19);
  *verified = atoi(tmp);
   
}







static void
report_success ( char *realname,  char *password)
{
    cs_set_value("realname", realname);
    cs_set_value("password", password);
    cs_set_int_value("success", 1);
}





static void show_verification_page(const char *key,  char *username,  char *id_number,  char *realname)
{
  
 char escaped_realname[MAX_NAME + 1];
 
 escape_realname(escaped_realname, realname);    /* shared_escape_realname.c */
  
  cs_set_value("username", username);
  cs_set_value("realname", escaped_realname);
  cs_set_value("realname2", realname);
  cs_set_value("id_number", id_number);

}




int
main ()
{

  SESSION user;
  char key[MAX_KEY + 1];
  char username[MAX_USERNAME + 1];
  char id_number[MAX_ID + 1];
  char realname[MAX_NAME + 1];
  char firstname[MAX_NAME + 1];
  char lastname[MAX_NAME + 1];
  int verified;
    
  char password[MAX_PASSWORD + 1];

  cs_cgi_init();

  read_parameters(key, username, id_number, realname,&verified);
  validate_super_key(key, &user);
  
  if(!verified)
     show_verification_page(key, username, id_number, realname);
  else
   {   
     get_first_last_names(realname, firstname, lastname);   /* shared_authenticate.c */

     derive_password (username, firstname, lastname, id_number, password,MAX_PASSWORD + 1);  /* shared_authenticate.c */
     write_central_password_file (username, password);   /* shared_encrypt.c */
     cs_set_event_msg();
     write_central_log(username, hdf_get_value(global_cgi->hdf, "log_event.reset_password",""), user.realname,0);  /* shared_central_log.c */
     report_success (realname, password);

  }
  cs_cgi_display("super_reset_password", 1);
  cs_cgi_destroy();
  return 0;
}

