#include "krb_locl.h"

RCSID("$Id: realm_parse.c,v 1.2 1996/06/07 19:44:16 joda Exp $");

static int
realm_parse(char *realm, int length, const char *file)
{
    FILE *F;
    char tr[128];
    char *p;
    
    if ((F = fopen(file,"r")) == NULL)
	return -1;
    
    while(fgets(tr, sizeof(tr), F)){
	p = strtok(tr, " \t\n\r");
	if(strcasecmp(p, realm) == 0){
	    fclose(F);
	    strncpy(realm, p, length);
	    return 0;
	}
    }
    fclose(F);
    return -1;
}

static const char *const files[] = KRB_CNF_FILES;

int
krb_realm_parse(char *realm, int length)
{
    int i;
  
    const char *dir = getenv("KRBCONFDIR");

    /* First try user specified file */
    if (dir != NULL){
	char fname[MaxPathLen];
	strncpy(fname, dir, sizeof(fname));
	strncat(fname, "/krb.conf", sizeof(fname));
	if (realm_parse(realm, length, fname) == 0)
	    return 0;
    }

    for (i = 0; files[i] != NULL; i++)
	if (realm_parse(realm, length, files[i]) == 0)
	    return 0;
    return -1;
}
