/*
 * pty.c - pty bindings for Lua
 * $Id: pty.c,v 1.3 2005/01/17 08:25:50 cpressey Exp $
 *
 * This file was derived in part from DragonFly BSD's
 * src/usr.bin/script/script.c, which contains the following license:
 */
/*
 * Copyright (c) 1980, 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>

#include <errno.h>
#include <libutil.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

#include "dfuibe_lua.h"

struct lua_pty {
	int		master;
	int		slave;
	pid_t		child;
};

LUA_CHECK_FUNCTION(pty, "Pty", struct lua_pty *)
LUA_PUSH_FUNCTION(pty, "Pty", struct lua_pty *)

/*** CONSTRUCTOR/DESTRUCTOR ***/

int 
lua_pty_open(lua_State *L)
{
	struct lua_pty *pty;

	pty = malloc(sizeof(struct lua_pty));
	if (openpty(&pty->master, &pty->slave, NULL, NULL, NULL) == -1) {
		lua_pushnil(L);
		return(1);
	}

	pty->child = fork();
	if (pty->child < 0) {
		lua_pushnil(L);
		return(1);
	}
	if (pty->child == 0)
	{
		const char *shell = "/bin/sh";

		close(pty->master);
		login_tty(pty->slave);
		execl(shell, shell, "-c", luaL_checkstring(L, 1), NULL);
		/* if we made it here, an error occurred! */
	}

	lua_push_pty(L, pty);
	return(1);
}

/******* METHODS *******/

int
lua_pty_read(lua_State *L)
{
	struct lua_pty *pty;
	long msec = 0;
	int n, cc;
	char obuf[1024];
	fd_set rfd;
	struct timeval tv;
	struct timeval *tvp = NULL;

	pty = lua_check_pty(L, 1);
	if (lua_isnumber(L, 2)) {
		msec = lua_tonumber(L, 2);
		tvp = &tv;
	}
	lua_pop(L, 2);

	FD_ZERO(&rfd);
	FD_SET(pty->master, &rfd);
	if (tvp != NULL) {
		tv.tv_sec = msec / 1000;
		tv.tv_usec = (msec % 1000) * 1000;
	}
	n = select(pty->master + 1, &rfd, 0, 0, tvp);
	if (n < 0) {
		lua_pushnil(L);
		lua_pushnumber(L, errno);
		return(2);
	}
	if (n > 0 && FD_ISSET(pty->master, &rfd)) {
		cc = read(pty->master, obuf, sizeof(obuf) - 1);
		if (cc <= 0) {
			lua_pushnil(L);
			lua_pushnumber(L, errno);
			return(2);
		} else {
			obuf[cc] = '\0';
			lua_pushstring(L, obuf);
			return(1);
		}
	} else {
		/* hunh? */
		lua_pushstring(L, "");
		return(1);
	}
}

int
lua_pty_write(lua_State *L)
{
	struct lua_pty *pty;
	const char *string;

	pty = lua_check_pty(L, 1);
	string = luaL_checkstring(L, 2);
	lua_pop(L, 2);

	write(pty->master, string, strlen(string));
	return(0);
}

int
lua_pty_close(lua_State *L)
{
	struct lua_pty *pty;
	pid_t pid;
	union wait status;
	int e = 0;

	pty = lua_check_pty(L, 1);
	while ((pid = wait3((int *)&status, WNOHANG, 0)) > 0) {
	        if (pid == pty->child) {
			if (WIFEXITED(status))
				e = WEXITSTATUS(status);
			else if (WIFSIGNALED(status))
				e = WTERMSIG(status);
			else // can't happen
				e = 1;
		}
	}

	lua_pushnumber(L, e);
	return(1);
}

/**** Binding Tables ****/

const luaL_reg pty_methods[] = {
	{"open",	lua_pty_open },
	{"read",	lua_pty_read },
	{"write",	lua_pty_write },
	{"close",	lua_pty_close },
	{0, 0}
};

const luaL_reg pty_meta_methods[] = {
/*	{"__gc", 	lua_pty_destroy }, */
	{0, 0}
};

/*** REGISTER ***/

LUA_API int
lua_pty_register(lua_State *L)
{
	luaL_openlib(L, "Pty", pty_methods, 0);		    /* fill methods table */
        luaL_openlib(L, "PtyMeta", pty_meta_methods,  0);   /* fill metatable */

	lua_set_instance_handler(L, "Pty", "PtyMeta");

	return(1);
}
