#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include "pw_check.h"
#include "config.h"

int pw_check(const char *prog_name, const struct passwd *pw, const char *pass) {
	if (pw->pw_passwd[0] == '\0' && pass[0] == '\0')
		return 0;

	if (pw->pw_passwd[0] == '!' || pw->pw_passwd[0] == '*') {
		if (prog_name)
			fprintf(stderr, "%s: Access denied\n", prog_name);

		return 1;
	}

	char *cpass = crypt(pass, pw->pw_passwd);
	if (cpass == NULL) {
		if (prog_name)
			fprintf(stderr, "%s: crypt: %s\n", prog_name, strerror(errno));

		return 1;
	}

	if (!strcmp(pw->pw_passwd, cpass))
		return 0;

	if (prog_name)
		fprintf(stderr, "%s: Incorrect password\n", prog_name);

	return 1;
}