/******************************************************************************
*   TinTin++                                                                  *
*   Copyright (C) 2004 (See CREDITS file)                                     *
*                                                                             *
*   This program is protected under the GNU GPL (See COPYING)                 *
*                                                                             *
*   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 *
*******************************************************************************/

/******************************************************************************
*                (T)he K(I)cki(N) (T)ickin D(I)kumud Clie(N)t                 *
*                                                                             *
*                         coded by Peter Unold 1992                           *
******************************************************************************/

#include "tintin.h"

#include <signal.h>
#include <sys/socket.h>

#include <sys/ioctl.h>
#include "prool.h"

/*************** globals ******************/

struct session *gts;
struct tintin_data *gtd;

// prool globals
struct termios new_terminal;
struct termios old_terminal;
//

void pipe_handler(int signal)
{
//	restore_terminal();

//	clean_screen(gtd->ses);

	tintin_printf(NULL, "#SOCKET ERROR: RECEIVED SIGPIPE.");

//	dump_stack();
}

/*
	when the screen size changes, take note of it
*/

void winch_handler(int signal)
{
	struct session *ses;

	init_screen_size(gts);

	for (ses = gts->next ; ses ; ses = ses->next)
	{
		init_screen_size(ses);

		if (HAS_BIT(ses->telopts, TELOPT_FLAG_NAWS))
		{
			send_sb_naws(ses, 0, NULL);
		}
	}

	/*
		we have to reinitialize the signals for sysv machines

	if (signal(SIGWINCH, winch_handler) == BADSIG)
	{
		syserr("signal SIGWINCH");
	}
	*/
}


void abort_handler(int signal)
{
	static char crashed = FALSE;

	if (crashed)
	{
		exit(-1);
	}
	crashed = TRUE;

	restore_terminal();

	clean_screen(gtd->ses);

	dump_stack();

	fflush(NULL);

	exit(-1);
}

void interrupt_handler(int signal)
{
	if (gtd->ses->connect_retry > utime())
	{
		gtd->ses->connect_retry = 0;
	}
	else if (HAS_BIT(gtd->ses->telopts, TELOPT_FLAG_SGA) && !HAS_BIT(gtd->ses->telopts, TELOPT_FLAG_ECHO))
	{
		socket_printf(gtd->ses, 1, "%c", 4);
	}
	else
	{
		cursor_delete_or_exit(gtd->ses, "");
	}
}

void suspend_handler(int signal)
{
	printf("\e[r\e[%d;%dH", gtd->ses->rows, 1);

	fflush(NULL);

	restore_terminal();

	kill(0, SIGSTOP);

	init_terminal();

	dirty_screen(gtd->ses);

	tintin_puts(NULL, "#RETURNING BACK TO TINTIN++.");
}

void trap_handler(int signal)
{
	static char crashed = FALSE;

	if (crashed)
	{
		exit(-1);
	}
	crashed = TRUE;

	restore_terminal();

	clean_screen(gtd->ses);

	dump_stack();

	fflush(NULL);

	exit(-1);
}


/****************************************************************************/
/* main() - show title - setup signals - init lists - readcoms - mainloop() */
/****************************************************************************/


int main(int argc, char **argv)
{
	int greeting = TRUE;
	char filename[256];
	char arg[BUFFER_SIZE];

	// prool
	tron=0; 
	total_log=1;
	coder=0;
	prool_loop_counter=0;
	start_time=time(0);
	watchdog=0;

	//if (greeting!=FALSE)prool_ident();

	prool_log("ProolTin started. http://prool.kharkov.org");
	prool_log("ProolTin repo: https://gitlab.com/prool/prooltin");
	prool_log("Compiling date " __DATE__ " " __TIME__);

	prooltranslate_init(greeting);

	//prool_log("Label #2");
	// end prool

	#ifdef SOCKS
		SOCKSinit(argv[0]);
	#endif

	if (signal(SIGTERM, trap_handler) == BADSIG)
	{
		syserr("signal SIGTERM");
	}

	if (signal(SIGSEGV, trap_handler) == BADSIG)
	{
		syserr("signal SIGSEGV");
	}

	if (signal(SIGHUP, trap_handler) == BADSIG)
	{
		syserr("signal SIGHUP");
	}

	if (signal(SIGABRT, abort_handler) == BADSIG)
	{
		syserr("signal SIGTERM");
	}
/*
	if (signal(SIGINT, interrupt_handler) == BADSIG)
	{
		syserr("signal SIGINT");
	}

	if (signal(SIGTSTP, suspend_handler) == BADSIG)
	{
		syserr("signal SIGSTOP");
	}
*/
	if (signal(SIGPIPE, pipe_handler) == BADSIG)
	{
		syserr("signal SIGPIPE");
	}

	if (signal(SIGWINCH, winch_handler) == BADSIG)
	{
		syserr("signal SIGWINCH");
	}

	if (argc > 1)
	{
		int c;

		while ((c = getopt(argc, argv, "a: e: G h r: s: t: v")) != EOF)
		{
			switch (c)
			{
				case 'G':
					greeting = FALSE;
					break;
			}
		}
	}

	init_tintin(greeting);

	sprintf(filename, "%s/%s", gtd->home, TINTIN_DIR);

	//printf("prooldebug filename='%s'\n", filename);

	if (mkdir(filename, 0777) || errno == EEXIST)
	{
		sprintf(filename, "%s/%s/%s", gtd->home, TINTIN_DIR, HISTORY_FILE);

		if (access(filename, F_OK ) != -1)
		{
			history_read(gts, filename);
		}
	}

	if (argc > 1)
	{
		int c;

		optind = 1;

		while ((c = getopt(argc, argv, "a: e: G h r: s: t: v")) != EOF)
		{
			switch (c)
			{
				case 'a':
					strcpy(arg, optarg);
					break;

				case 'e':
					gtd->quiet++;
					gtd->ses = script_driver(gtd->ses, LIST_COMMAND, optarg);
					gtd->quiet--;
					break;

				case 'G':
					break;

				case 'h':
					tintin_printf(NULL, "Usage: %s [OPTION]... [FILE]...", argv[0]);
					tintin_printf(NULL, "");
					tintin_printf(NULL, "  -a  Set argument for PROGRAM START event.");
					tintin_printf(NULL, "  -e  Execute given command.");
					tintin_printf(NULL, "  -G  Don't show the greeting screen.");
					tintin_printf(NULL, "  -h  This help section.");
					tintin_printf(NULL, "  -r  Read given file.");
					tintin_printf(NULL, "  -t  Set given title.");
					tintin_printf(NULL, "  -v  Enable verbose mode.");

					restore_terminal();
					exit(1);
					break;

				case 'r':
					gtd->ses = do_read(gtd->ses, optarg);
					break;

				case 't':
					printf("\e]0;%s\007", optarg);
					break;

				case 'v':
					do_configure(gtd->ses, "{VERBOSE} {ON}");
					break;

				default:
					tintin_printf(NULL, "Unknown option '%c'.", c);
					break;
			}
		}

		if (argv[optind] != NULL)
		{
			gtd->ses = do_read(gtd->ses, argv[optind]);
		}
	}

	check_all_events(gts, SUB_ARG, 0, 3, "PROGRAM START", CLIENT_NAME, CLIENT_VERSION, arg);
	check_all_events(gts, SUB_ARG, 0, 2, "SCREEN RESIZE", ntos(gts->cols), ntos(gts->rows));

	mainloop();

	return 0;
}

void init_tintin(int greeting)
{
	int ref, index;

	gtd            = (struct tintin_data *) calloc(1, sizeof(struct tintin_data));

	gtd->ses = gts = (struct session *) calloc(1, sizeof(struct session));

	gtd->str_size       = sizeof(struct str_data);
	gtd->str_hash_size  = sizeof(struct str_hash_data);

	for (index = 0 ; index < LIST_MAX ; index++)
	{
		gts->list[index] = init_list(gts, index, 32);
	}

	gts->name           = strdup("gts");
	gts->group          = strdup("");
	gts->session_host   = strdup("");
	gts->session_port   = strdup("");
	gts->cmd_color      = strdup("");
	gts->telopts        = TELOPT_FLAG_ECHO;
	gts->flags          = SES_FLAG_MCCP;
	gts->socket         = 1;
	gts->read_max       = 16384;
	gts->lognext_name   = strdup("");
	gts->logline_name   = strdup("");


	gtd->flags          = TINTIN_FLAG_INHERITANCE;

	gtd->mccp_len       = 4096;
	gtd->mccp_buf       = (unsigned char *) calloc(1, gtd->mccp_len);

	gtd->mud_output_max = 16384;
	gtd->mud_output_buf = (char *) calloc(1, gtd->mud_output_max);

	gtd->input_off      = 1;

	gtd->home           = strdup(getenv("HOME") ? getenv("HOME") : ".");
	gtd->lang           = strdup(getenv("LANG") ? getenv("LANG") : "UNKNOWN");
	gtd->term           = strdup(getenv("TERM") ? getenv("TERM") : "UNKNOWN");

	for (index = 0 ; index < 100 ; index++)
	{
		gtd->vars[index] = strdup("");
		gtd->cmds[index] = strdup("");
	}

	for (ref = 0 ; ref < 26 ; ref++)
	{
		for (index = 0 ; *command_table[index].name != 0 ; index++)
		{
			if (*command_table[index].name == 'a' + ref)
			{
				gtd->command_ref[ref] = index;
				break;
			}
		}
	}

	init_screen_size(gts);

	init_local(gts);

	printf("\e="); // set application keypad mode

	gtd->input_level++;

	do_configure(gts, "{AUTO TAB}         {5000}");
	do_configure(gts, "{BUFFER SIZE}     {20000}");
	do_configure(gts, "{COLOR MODE}       {AUTO}");
	do_configure(gts, "{COLOR PATCH}       {OFF}");
	do_configure(gts, "{COMMAND COLOR}   {<078>}");
	do_configure(gts, "{COMMAND ECHO}       {ON}");
	do_configure(gts, "{CONNECT RETRY}       {0}");
	do_configure(gts, "{CHARSET}         {UTF-8}"); // prool: forced UTF-8
	do_configure(gts, "{HISTORY SIZE}     {1000}");
	do_configure(gts, "{LOG}               {RAW}");
	do_configure(gts, "{MOUSE TRACKING}    {OFF}");
	do_configure(gts, "{PACKET PATCH}     {0.00}");
	do_configure(gts, "{RANDOM SEED}      {AUTO}");
	do_configure(gts, "{REPEAT CHAR}         {!}");
	do_configure(gts, "{REPEAT ENTER}      {OFF}");
	do_configure(gts, "{SCREEN READER}     {OFF}");
	do_configure(gts, "{SCROLL LOCK}        {ON}");
	do_configure(gts, "{SPEEDWALK}         {OFF}");
	do_configure(gts, "{TINTIN CHAR}         {#}");
	do_configure(gts, "{VERBATIM}          {OFF}");
	do_configure(gts, "{VERBATIM CHAR}      {\\}");
	do_configure(gts, "{VERBOSE}           {OFF}");
	do_configure(gts, "{WORDWRAP}           {ON}");

	gtd->input_level--;

	insert_node_list(gts->list[LIST_PATHDIR],  "n",  "s",  "1");
	insert_node_list(gts->list[LIST_PATHDIR],  "e",  "w",  "2");
	insert_node_list(gts->list[LIST_PATHDIR],  "s",  "n",  "4");
	insert_node_list(gts->list[LIST_PATHDIR],  "w",  "e",  "8");
	insert_node_list(gts->list[LIST_PATHDIR],  "u",  "d", "16");
	insert_node_list(gts->list[LIST_PATHDIR],  "d",  "u", "32");

	insert_node_list(gts->list[LIST_PATHDIR], "ne", "sw",  "3");
	insert_node_list(gts->list[LIST_PATHDIR], "nw", "se",  "9");
	insert_node_list(gts->list[LIST_PATHDIR], "se", "nw",  "6");
	insert_node_list(gts->list[LIST_PATHDIR], "sw", "ne", "12");

	init_terminal();

	if (greeting)
	{
		do_advertise(gts, "");

		if (gts->cols >= 80)
		{
			do_help(gts, "GREETING");
		}
		else
		{
			tintin_printf2(gts,
				"\e[0;37mT I N T I N + +   %s"
				"\n\n\e[0;36mT\e[0;37mhe K\e[0;36mi\e[0;37mcki\e[0;36mn\e[0;37m \e[0;36mT\e[0;37mickin D\e[0;36mi\e[0;37mkuMUD Clie\e[0;36mn\e[0;37mt\n\n"
				"Code by Peter Unold, Bill Reis, and Igor van den Hoven\n",
				CLIENT_VERSION);
			prool_ident();
		}
	}
}


void quitmsg(char *message)
{
	struct session *ses;

	SET_BIT(gtd->flags, TINTIN_FLAG_TERMINATE);

	while ((ses = gts->next) != NULL)
	{
		cleanup_session(ses);
	}

	if (gtd->chat)
	{
		close(gtd->chat->fd);
	}

	check_all_events(gts, SUB_ARG, 0, 1, "PROGRAM TERMINATION", message ? message : "");

	if (gtd->history_size)
	{
		char filename[BUFFER_SIZE];

		sprintf(filename, "%s/%s/%s", gtd->home, TINTIN_DIR, HISTORY_FILE);

		history_write(gts, filename);
	}

	restore_terminal();

	clean_screen(gts);

	if (message == NULL || *message)
	{
		if (message)
		{
			printf("\n%s", message);
		}
		printf("\nGoodbye from TinTin++\n\n");
	// prool
	uptime_();
	prool_log("ProolTin ended");

	if ((watchdog==0) && (total_log==1)) {
	printf("Delete log (y,N) ? ");

#ifdef MACOS
init_terminal_from_tintin();
#else
	/* prool: set stdin (file descriptor=0) to NOraw mode */
	struct termio tstdin;
	ioctl(0, TCGETA, &tstdin);
	tstdin.c_lflag &= ~(ICANON);
	ioctl(0, TCSETA, &tstdin);
#endif

	char c=getchar();

#ifdef MACOS
restore_terminal_from_tintin();
#else
	ioctl(0, TCGETA, &tstdin);
	tstdin.c_lflag |= (ICANON);
	ioctl(0, TCSETA, &tstdin);
#endif

	puts("");
	if ((c=='y')||(c=='Y')) unlink ("prooltin.log");
	} // end if (watchdog==0)
	// end prool
	}
	fflush(NULL);

	exit(0);
}

// prool: code from pacmancraft

void init_terminal_from_tintin(void)
{
	struct termios io;

	if (tcgetattr(0, &old_terminal))
	{
		perror("tcgetattr");

		exit(-1);
	}

	io = old_terminal;

	/*
		Canonical mode off
	*/

	DEL_BIT(io.c_lflag, ICANON);

	io.c_cc[VMIN]   = 1;
	io.c_cc[VTIME]  = 0;
	io.c_cc[VSTART] = 255;
	io.c_cc[VSTOP]  = 255;
	io.c_cc[VINTR]  = 4; // ctrl-d

	/*
		Make the terminalal as raw as possible
	*/

	DEL_BIT(io.c_lflag, ECHO|ECHONL|IEXTEN|ISIG);

	SET_BIT(io.c_cflag, CS8);

	if (tcsetattr(0, TCSANOW, &io))
	{
		perror("tcsetattr");

		exit(-1);
	}

	if (tcgetattr(0, &new_terminal))
	{
		perror("tcgetattr");

		exit(-1);
	}
}

void restore_terminal_from_tintin(void)
{
	tcsetattr(0, TCSANOW, &old_terminal);

	printf("\e[?1000l\e[?1002l\e[?1004l\e[?1006l");
}
