#ifdef HAVE_CONFIG_H
#include <config.h>
RCSID("$Id: get_default_principal.c,v 1.4 1996/06/01 00:05:04 assar Exp $");
#endif

#include "krb_locl.h"
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif

int
krb_get_default_principal(char *name, char *instance, char *realm)
{
  char *file;
  int ret;

  char *p;

  if ((file = getenv("KRBTKFILE")) == NULL)
      file = TKT_FILE;  
  
  ret = krb_get_tf_fullname(file, name, instance, realm);
  if(ret == KSUCCESS)
      return 0;

#ifdef HAVE_PWD_H
  {
    struct passwd *pw;
    pw = getpwuid(getuid());
    if(pw == NULL){
      return -1;
    }

    strcpy(name, pw->pw_name);
    strcpy(instance, "");
    krb_get_lrealm(realm, 1);

    if(strcmp(name, "root") == 0){
      p = NULL;
#if defined(HAVE_GETLOGIN) && !defined(POSIX_GETLOGIN)
      p = getlogin();
#endif
      if(p == NULL)
	p = getenv("USER");
      if(p == NULL)
	p = getenv("LOGNAME");
      if(p){
	strcpy(name, p);
	strcpy(instance, "root");
      }
    }
    return 1;
  }
#endif
  return -1;
}
