/* 
 * Authentication Layer
 * 
 * auth.c
 *
 * Interface to the authentication layer.
 * 
 */

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "auth.h"


/*
 * auth_filename: the file name with the users data
 */
static char auth_filename[MAX_FILENAME_SIZE];


/*
 * auth_total: the total number of users
 */
static int auth_total;


int auth_new(char *filename) {
	FILE *fp = NULL;
	char temp_username[MAX_USERNAME_SIZE];
	char temp_password[MAX_PASSWORD_SIZE];
	
	strncpy(auth_filename, filename, MAX_FILENAME_SIZE - 1);

	fp = fopen(auth_filename, "r");

	if (fp == NULL) {
		return -1;
	}
		
	for (auth_total = 0; fscanf(fp, "%s\t%s", temp_username, temp_password) != EOF; auth_total++);	
	
	fclose(fp);
	
	printf("\33[1m[auth_new]\33[0m '%s' loaded.\n", filename);

	return 0;
}


int auth_login(char* username, char *password) {
	FILE *fp = fopen(auth_filename, "r");
	char temp_username[MAX_USERNAME_SIZE];
	char temp_password[MAX_PASSWORD_SIZE];
	
	for (int i = 1; fscanf(fp, "%s\t%s", temp_username, temp_password) != EOF; i++) {
		if (strcmp(username, temp_username) == 0
			&& strcmp(password, temp_password) == 0) {
			fclose(fp);
			
			return i;
		}
	}
	
	fclose(fp);
	
	return 0;
}


int auth_lookup(char* username) {
	FILE *fp = fopen(auth_filename, "r");
	char temp_username[MAX_USERNAME_SIZE];
	char temp_password[MAX_PASSWORD_SIZE];
	
	for (int i = 1; fscanf(fp, "%s\t%s", temp_username, temp_password) != EOF; i++) {
		if (strcmp(username, temp_username) == 0) {
			fclose(fp);
			
			return i;
		}
	}
	
	fclose(fp);
	
	return 0;
}


int auth_total_users() {
	return auth_total;
}


void auth_dump() {
	FILE *fp = fopen(auth_filename, "r");
	int c;
	
	printf("Users:\n");
	
	while ((c = fgetc(fp)) != EOF) {
		printf("%c", c);
	}
	
	fclose(fp);
}
