/*
 *
 * Minimal getty funcionality to allow ipod to run 
 * applications in the shell after booting.
 *
 *
 * usage: ipodgetty program
 *   i.e: ipodgetty /bin/Sash
 *
 * by Jacobo Avariento Gimeno (jack at gulcas.org)
 *
 *
 * Based on the code of rungetty.c
 *
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>

/* #define TTY "/dev/tty1"  */
#define TTY "/dev/vc/1"

void error(char *msg) {
	int fd;
	if ((fd=open("/dev/console", 1)) >= 0)
		write(fd, msg, strlen(msg));
	exit(1);
}

void debug(char *msg) {
	int fd;
	if ((fd=open("/dev/console", 1)) >= 0)
		write(fd, msg, strlen(msg));
}

int main(int argc, char **argv) {
	int fd;
	
	if (argc != 2)
		error("Bad usage: ipodgetty program.\n");
	
	if (chown(TTY, 0, 0) || chmod(TTY, 0600))
		error("Error: chown/chmod.\n");
	
	if ((fd=open(TTY, O_RDWR, 0)) < 0 )//|| ioctl(fd, TIOCSTTY, (void*1) == -1)
		error("Error: cannot open tty.\n");

	if (!isatty(fd))
		error("Error: not a tty.\n");

	//vhangup(); /* inside unistd.h */
	/*
	 * Revoke access permissions to all processes currently 
	 * communicating with the control terminal, and then send 
	 * a SIGHUP signal to the process group of the control terminal.
 	 * extern int vhangup (void) __THROW;
	 *
	 */
	
	close(2);
	close(1);
	close(0);
	close(fd);

	if (open(TTY, O_RDWR, 0) != 0)
		error("Error: Cannot open tty as stdin.\n");
	
	if (dup(0) != 1 || dup(0) != 2)
		error("Error: dup problems.\n");

	//write(0, "\033c", 2); /* clear the screen */

	putenv("TERM=linux");
	putenv("PATH=/bin:/");

	ioctl(0, TCFLSH, 2);
	
	setgid(0); setuid(0);
	
	execl("/bin/Sash", "Sash", 0);

	error("ERROR:execve");
}
