/* Copyright 1990, Daniel J. Bernstein. All rights reserved. */

#include "config.h"
#include <strings.h>
#include <stdio.h>
#include <pwd.h>
extern char *getenv(); /* grrrr */
extern char *ttyname(); /* grrrr */
#include "pty.h"
#include "misc.h"

int sessdir()
{
 char suid[10];
 char *home;

 if (flagxsetuid)
  {
   if (chdir(PTYDIR) == -1)
     return -1;
  }
 else
  {
   if ((home = getenv("HOME")) == 0)
     return -1;
   else if (chdir(home) == -1)
     return -1;
   else if ((chdir(".pty") == -1)
          &&((mkdir(".pty",0700) == -1)
           ||(chdir(".pty") == -1)))
          return -1;
  }

 (void) sprintf(suid,"%d",uid);
 if ((chdir(suid) == -1)
   &&((mkdir(suid,0700) == -1)
    ||(chdir(suid) == -1)))
   return -1;
 return 0;
}

char *real_ttyname(fd)
int fd; /* first guess; should be /dev/tty */
{
 char *ttyn;

 if ((ttyn = ttyname(fd))
   &&(strcmp(ttyn,"/dev/tty")))
  {
   /* This would actually happen if opening /dev/tty converted into */
   /* opening the actual terminal device---which would be nice. */
   return ttyn;
  }
 /* So much for nice tries. */
 for (fd = getdtablesize();fd >= 0;fd--)
  {
   if ((ttyn = ttyname(fd))
     &&(strcmp(ttyn,"/dev/tty")))
     return ttyn;
  }
 return (char *) 0;
}

static struct passwd *pw;
static char nopwun[12];

void setusername()
{
 if (pw = getpwuid(uid))
   username = pw->pw_name;
 else
  {
   (void) sprintf(nopwun,"%d",uid);
   username = nopwun;
  }
}
