/*
 * devname.c
 *
 */
#define __KERNEL__
#include <sys/types.h>
#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pwd.h>
#include <errno.h>
#include <ctype.h>
#include <time.h>
#include <sys/ioctl.h>
#include <linux/sched.h>
#include <linux/ptrace.h>
#include <limits.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include "ps.h"

char *
dev_to_tty(int dev)
{
    char *tty;
    static char name[8];

    if (dev == -1)
	return "?";
    tty = find_tty(dev);
    if (tty)
	return tty;
    sprintf(name, "%d,%d", major(dev), minor(dev));
    return name;
}

int
tty_to_dev(char *tty)
{
    struct stat statbuf;
    char path[PATH_MAX];

    if (*tty == '\0') {		/* empty string: controlling terminal */
	if ((fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode))
	    || (fstat(1, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode))
	    || (fstat(2, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)))
	    return statbuf.st_rdev;
	else
	    return -1;
    }
    if (strcmp(tty, "?") == 0)
	return -1;
    if (strcmp(tty, "co") == 0)
	tty = "console";
    if (stat(tty, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode))
	return statbuf.st_rdev;
    sprintf(path, "/dev/%s", tty);
    if (stat(path, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode))
	return statbuf.st_rdev;
    sprintf(path, "/dev/tty%s", tty);
    if (stat(path, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode))
	return statbuf.st_rdev;
    fprintf(stderr, "the name `%s' is not a tty\n", tty);
    exit(1);
}
