/* password.c - set password for an account
 */

#define _XOPEN_SOURCE
#define _XOPEN_VERSION 4
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <pwd.h>
#include "terminal.h"
#include "examine.h"
#include "bbs.h"


/* Allow the user to set the password for "user".
 */
void examine_password(char *user)
{
	char *sc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	    "abcdefghijklmnopqrstuvwxyz" "0123456789" "./";
	char salt[3];
	char key[64];
	char *a;
	char *b;
	char *c;

	if (examine_priv_check(user))
		return;

	if (!strcmp(current_user, "guest"))
		return;

	examine_udb_load(user);

	rf_redraw = 1;

	t_goto(0, t_rows - 1);
	t_clrtoeol();

	a = examine_udb_env("BBS_PASS");
	if ((strcmp(current_user, user) == 0) && (a[0] != 0)) {
		b = getpass("Enter CURRENT password: ");
		if (!b)
			return;
		salt[0] = a[0];
		salt[1] = a[1];
		salt[2] = 0;
		c = crypt(b, salt);
		if (strcmp(c, a) != 0) {    /* typed password incorrect */
			t_goto(0, t_rows - 1);
			t_clrtoeol();
			t_centre
			    ("\035R  *** Incorrect password ***  \035r");
			sleep(1);
			return;
		}
	}

	b = getpass("Enter NEW password: ");
	if (!b)
		return;
	strncpy(key, b, sizeof(key) - 1);

	b = getpass("Re-enter NEW password: ");
	if (!b)
		return;
	if (strcmp(b, key) != 0) {
		t_goto(0, t_rows - 1);
		t_clrtoeol();
		t_centre("\035R  *** Passwords do not match ***  \035r");
		sleep(1);
		return;
	}

	srand(time(0) ^ getpid() ^ getppid());

	salt[0] = sc[rand() % strlen(sc)];  /* choose new salt */
	salt[1] = sc[rand() % strlen(sc)];

	if (!strcmp(key, "")) {
		examine_udb_env_set("BBS_PASS", "");
	} else {
		examine_udb_env_set("BBS_PASS", crypt(key, salt));
	}

	examine_udb_save(user);

	t_goto(0, t_rows - 1);
	t_clrtoeol();
	t_centre("\035R  --- Password changed ---  \035r");
	sleep(1);
}

/* EOF */
