#include <time.h>
#include <stdio.h>
#include <string.h>
#include "b64.h"
#include "mincrypt.h"

extern char *crypt(const char *key, const char *setting);

char *shash(char *a, char *b)
{
    static char out[256];
    time_t tczas;
    long int k = 0;
    int i;

    time(&tczas);
    k = (long int) tczas;

    for (i = 0; i < strlen(a); i++)
	k = labs((k * (i + 1) * (short int) a[i]) % 99999999);
    for (i = 0; i < strlen(b); i++)
	k = labs((k * (i + 1) * (short int) b[i]) % 99999999);

    snprintf(out, sizeof(out), "01%ld", k);
    return out;
}

int mincrypt(char *line, char *orgnick, char *orgpass, int aauth)
{
    char buf[500];
    int l;
    char *nick, *pass;
    char *pom;

    if (!aauth) {
	pom = (char *) index(line, ':');
	if (!pom)
	    return 0;
	pom += 8;
	l = b64_decode(pom, buf, 499);
	buf[l] = 0;
	nick = buf;
	pass = (char *) index(nick, ':');
	if (!pass)
	    return 0;
	pass++[0] = 0;
    }
    else {
	snprintf(buf, sizeof(buf), "%s", line);
	pom = (char *) index(buf, ';');
	if (!pom)
	    return 0;
	if (strlen(pom) < 2)
	    return 0;
	pom = (char *) index(pom + 1, ';');
	if (!pom)
	    return 0;
	if (strlen(pom++) < 2)
	    return 0;
	nick = pom;
	pass = (char *) index(pom, ';');
	if (!pass)
	    return 0;
	if (strlen(pass) < 2)
	    return 0;
	pass++[0] = 0;
	pom = (char *) index(pass, ' ');
	if (!pom)
	    return 0;
	pom[0] = 0;
    }
// printf("mincrypt: %s %s %s %s\n",nick,orgnick,orgpass,crypt(pass,orgpass));
    if ((strcmp(crypt(pass, orgpass), orgpass) == 0)
	&& (strcmp(nick, orgnick) == 0))
	return 1;
    else
	return 0;
}
