/* Author: Ram Samudrala (me@ram.org)
 *
 * January 1, 1997. 
 */

#include "cgi_common.h"
#include "cgi_defines.h"
#include "cgi_error_handlers.h"
#include "login_defines.h"

/******************************************************************/

/* From local_passwd.c (C) Regents of Univ. of California blah blah */
static unsigned char itoa64[] =         /* 0 ... 63 => ascii - 64 */
        "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

/* char *crypt(char *pw, char *salt); */
/* why aren't these prototyped in include */

/******************************************************************/

void to64(register char *s, register long v, register int n)
{
  while (--n >= 0) 
    {
      *s++ = itoa64[v&0x3f];
      v >>= 6;
    }
}

/******************************************************************/

char *strd(char *s) 
{
  char *d;
  
  d=(char *)malloc(strlen(s) + 1);
  strcpy(d,s);
  return(d);
}

/******************************************************************/

void add_password(char username[], char password[], char password_filename[])
{
  char *pw, *cpw, salt[3];
  FILE *password_fp;
  
  pw = strd(password);
  (void) srand ((int) time ((time_t *) NULL));
  to64(&salt[0],rand(), 2);
  cpw = crypt(pw, salt);
  free(pw);

  open_file(&password_fp,  password_filename, "a", "add_password");
  fprintf(password_fp, "%s:%s\n", username, cpw);
  close_file(&password_fp, password_filename, "add_password");

  return;
}

/******************************************************************/

void modify_password(char username[], char password[], char password_filename[])
{
  char *pw, *cpw, salt[3];
  char password_line[MAX_USERS][PASSWORD_LINE_LENGTH];
  FILE *password_fp;
  int i, password_found = FALSE;

  if (strcmp(password, DELETE_PROFILE_COMMAND) != 0)
    {
      pw = strd(password);
      (void) srand ((int) time ((time_t *) NULL));
      to64(&salt[0],rand(), 2);
      cpw = crypt(pw, salt);
      free(pw);
    }
  
  for(i = 0; i < MAX_USERS; i++)
    password_line[i][0] = '\0';
  
  open_file(&password_fp,  password_filename, "r", "modify_password");
  for(i = 0; fgets(password_line[i], PASSWORD_LINE_LENGTH, password_fp); i++)
    if ((!password_found) && (strstr(password_line[i], username)))
      {
	password_found = TRUE;
	if (strcmp(password, DELETE_PROFILE_COMMAND) == 0)
	  password_line[i][0] = '\0';
	else
	  sprintf(password_line[i], "%s:%s\n", username, cpw);
      }
  close_file(&password_fp, password_filename, "modify_password");

  if (!password_found)
    display_error("modify_password(): password not found!");
  
  open_file(&password_fp,  password_filename, "w", "modify_password");
  for(i = 0; i < MAX_USERS; i++)
    if (password_line[i][0] != '\0')
      fprintf(password_fp, "%s", password_line[i]);
  close_file(&password_fp, password_filename, "modify_password");

  return;
}

/******************************************************************/

