#include <hesiod.h>
#include <pwd.h>
#include <string.h>

struct passwd *
ath_fixhome(pw, uname)
     struct passwd *pw;
     char *uname;
{
  char **hes, *sp;
  static struct passwd foo;
  static char savename[32], savehome[256];

  /* Get locker info from Hesiod */
  hes=hes_resolve(uname, "filsys");
  if (!hes || !hes[0] || strncmp(hes[0], "AFS ", 4)) return NULL;
  strcpy(savehome, hes[0]);
  sp=strchr(savehome, ' ');
  if (sp) *sp='\0';

  /* If we got non-NULL pw, we're done. */
  if (pw)
    {
      pw->pw_dir = savehome;
      return pw;
    }

  /* Fill in fake info */
  memset(&foo, 0, sizeof(foo));
  foo.pw_name = strcpy(savename, uname);
  foo.pw_uid = 32767;		/* nobody */
  foo.pw_gid = 101;		/* MIT */
  foo.pw_dir = savehome;
  foo.pw_shell = "/dev/null";
  return &foo;
}

struct passwd *
ath_getpwnam(uname)
     const char *uname;
{
  struct passwd *retval;

  /* get local info */
  retval = getpwnam(uname);
  
  /* get hesiod info */
  if (!retval)
    retval = hes_getpwnam(uname);

  /* change homedir if applicable */
  return ath_fixhome(retval);
}

struct passwd *
ath_getpwuid(uid)
     uid_t uid;
{
  struct passwd *retval;

  /* get local info */
  retval = getpwuid(uid);
  
  /* get hesiod info */
  if (!retval)
    retval = hes_getpwuid(uid);

  /* change homedir if applicable */
  return ath_fixhome(retval);
}
