/*******************************************************************************

  Copyright(c) 2003-2004 Aurelien Reynaud.

  This program is free software; you can redistribute it and/or modify it
  under the terms of the GNU General Public License as published by the Free
  Software Foundation; either version 2 of the License, or (at your option)
  any later version.

  This program is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
  more details.

  You should have received a copy of the GNU General Public License along with
  this program; if not, write to the Free Software Foundation, Inc., 59
  Temple Place - Suite 330, Boston, MA  02111-1307, USA.

  The full GNU General Public License is included in this distribution in the
  file called COPYING.

*******************************************************************************/

/* Note: this was shamelessly stolen from an old uClibc source...
 */

/* Make FD be the controlling terminal, stdin, stdout, and stderr;
   then close FD.  Returns 0 on success, nonzero on error.  */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "ggiterm.h"
#include "debug.h"

#include <sys/param.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <utmp.h>

int login_tty (int fd)
{
	debug (DEBUG_FUNCTION, "custom login_tty called with args (file descriptor)");
	
	(void) setsid ();
#ifdef TIOCSCTTY
	if (ioctl (fd, TIOCSCTTY, (char*)NULL) == -1) {
		debug (DEBUG_FUNCTION, "Leaving");
		return -1;
	}
#else
	/* This might work.  */
	char *fdname = ttyname (fd);
	int newfd;
	if (fdname) {
		if (fd != 0)
			(void) close (0);
		if (fd != 1)
			(void) close (1);
		if (fd != 2)
			(void) close (2);
		newfd = open (fdname, O_RDWR);
		(void) close (newfd);
	}
#endif
	(void) dup2(fd, 0);
	(void) dup2(fd, 1);
	(void) dup2(fd, 2);
	if (fd > 2)
		(void) close(fd);
	debug (DEBUG_FUNCTION, "Leaving");
	return 0;
}
