/* create.c - create a new account
 */

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <pwd.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "terminal.h"
#include "examine.h"
#include "bbs.h"


/* Allow the user to create a new account while examining "user".
 */
void examine_create(char *user)
{
	struct passwd *z;
	char tbuf[16];
	char buf[1024];
	FILE *fptr;
	char *a;
	int n;

	rf_redraw = 1;

	tbuf[0] = 0;
	do {
		n = t_input("Create new account: ", tbuf,
			    sizeof(tbuf) - 1);
	} while (n == 1);

	if (tbuf[0] < 32)
		return;
	if (strchr(tbuf, '.') || strchr(tbuf, '/') || strchr(tbuf, ' '))
		return;

	strcpy(buf, cf_str("udb"));
	a = strrchr(buf, '/');
	if (!a)
		return;
	sprintf(a, "/%s", tbuf);

	fptr = fopen(buf, "r");
	if (fptr) {			    /* check user doesn't already exist */
		fclose(fptr);
		t_goto(0, t_rows - 1);
		t_clrtoeol();
		sprintf(buf,
			"\035R  *** Account `%s' already exists ***  \035r",
			tbuf);
		t_centre(buf);
		sleep(2);
		return;
	}

	z = getpwnam(tbuf);
	if (z) {			    /* check internal account doesn't exist */
		t_goto(0, t_rows - 1);
		t_clrtoeol();
		sprintf(buf,
			"\035R  *** Account `%s' already exists in Unix ***  \035r",
			tbuf);
		t_centre(buf);
		sleep(2);
		return;
	}

	fptr = fopen(buf, "w");		    /* create blank UDB file */
	if (!fptr) {
		t_goto(0, t_rows - 1);
		t_clrtoeol();
		sprintf(buf,
			"\035R  *** Failed to create account `%s' (%s) ***  \035r",
			tbuf, strerror(errno));
		t_centre(buf);
		sleep(2);
		return;
	}

	fprintf(fptr,
		"BBS_PRIVS=\n"
		"BBS_BANS=\n"
		"BBS_LEVEL=10\n"
		"BBS_EMAIL=unknown\n"
		"MVIEW_NAMELINE=%s\n"
		"BBS_LOGINS=0\n"
		"BBS_LOGOUT=Never logged out\n" "BBS_PASS=\n", tbuf);

	fclose(fptr);

	chmod(buf, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);

	t_goto(0, t_rows - 1);
	t_clrtoeol();
	sprintf(buf, "\035R  --- Account `%s' created ---  \035r", tbuf);
	t_centre(buf);
	sleep(2);
}

/* EOF */
