/* Copyright (C) 2010,2012-2013 G.P. Halkes
   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License version 3, as
   published by the Free Software Foundation.

   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, see <http://www.gnu.org/licenses/>.
*/

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/ioctl.h>

#include "optionMacros.h"
#include "replay.h"
#include "common.h"
#include "input.h"

/* TODO: allow user to specify different client to start from the command line */

static int master;
static pid_t pid;
static td_bool resize_capable;
static const char *directory;
static char *output;
static FILE *output_file;
static char *input;
static td_bool strip_location_reports = td_true;

static void printUsage(void) {
	printf("Usage: tdrerecord [OPTIONS] <recording>\n");
	printf("  -d<dir>,--directory=<dir>           Save recording in directory <dir>\n");
	printf("  -o<file>,--output=<file>            Save recording as <file>\n");
	printf("  -V, --version                       Print version and copyright information\n");
	printf("  -l, --no-strip-location-reports     Don't strip the location reports from the\n"
	       "                                        'send' strings\n");
	exit(EXIT_SUCCESS);
}

static PARSE_FUNCTION(parse_options)
	OPTIONS
		OPTION('o', "output", REQUIRED_ARG)
			output = optArg;
		END_OPTION
		OPTION('d', "directory", REQUIRED_ARG)
			directory = optArg;
		END_OPTION
		OPTION('h', "help", NO_ARG)
			printUsage();
		END_OPTION
		OPTION('V', "version", NO_ARG)
			fputs("tdrerecord " VERSION_STRING "\nCopyright (C) 2010,2013 G.P. Halkes\nLicensed under the GNU General Public License version 3\n", stdout); /* @copyright */
			exit(0);
		END_OPTION
		OPTION('l', "no-strip-location-reports", NO_ARG)
			strip_location_reports = td_false;
		END_OPTION
		DOUBLE_DASH
			NO_MORE_OPTIONS;
		END_OPTION

		fatal("Unknown option " OPTFMT "\n", OPTPRARG);
	NO_OPTION
		if (input != NULL)
			fatal("More than one replay specified\n");
		input = optcurrent;
	END_OPTIONS
	if (input == NULL)
		fatal("No replay specified\n");

	if (output != NULL && directory != NULL)
		fatal("Can only specify one of --output and --directory\n");
END_FUNCTION

static void set_window_size(ExpNode *size) {
	struct winsize wsz;
	memset(&wsz, 0, sizeof(wsz));

	interact_loop(master, pid, output_file, size->un.size.delay);
	fprintf(output_file, "window_size %d %d", size->un.size.columns, size->un.size.rows);
	if (size->un.size.delay > 0) {
		fprintf(output_file, " %d", size->un.size.delay);
		if (size->un.size.min_delay)
			fprintf(output_file, " >%d", size->un.size.min_delay);
	}
	fputc('\n', output_file);
	/* Resync timestamp */
	init_timestamp();

	if (resize_capable) {
		char buffer[64];
		size_t result;
		/* FIXME: this should use tparm or similar to ensure proper padding etc. */
		result = sprintf(buffer, "\x1b[8;%d;%dt", size->un.size.rows, size->un.size.columns);
		safe_write(STDOUT_FILENO, buffer, result);
		/* FIXME: wait for terminal to respond because otherwise the next updates may fail. */
	}
	wsz.ws_col = size->un.size.columns;
	wsz.ws_row = size->un.size.rows;
	if (ioctl(master, TIOCSWINSZ, &wsz))
		fatal("Error setting window size: %s\n", strerror(errno));
}

static void send_keys(ExpNode *keys) {
	StringListNode *current = keys->un.args;

	for (; current != NULL; current = current->next) {
		/* If the delay is very small, just send now before the terminal decides to continue.
		   This should solve issues like the one with vi, which sends information requests
		   to the terminal and then doesn't wait for the response. */
		if (current->delay >= 5) {
			int status = interact_loop(master, pid, output_file, current->delay);
			if (status != -1) {
				fclose(output_file);

				reset_tty();
				fprintf(stderr, "-- recording is saved in %s --\n", output);
				exit(WEXITSTATUS(status));
			}
		}

		if (strip_location_reports) {
			int i, j;
			for (i = 0; i < current->length; i++) {
				if (current->string[i] == 27 && i + 1 < current->length && current->string[i + 1] == '[') {
					for (j = i + 2; j < current->length &&
							((current->string[j] >= '0' && current->string[j] <= '9') || current->string[j] == ';'); j++) {}
					if (j < current->length && current->string[j] == 'R') {
						memmove(current->string + i, current->string + j + 1, current->length - j - 1);
						current->length -= j + 1 - i;
						i--;
					}
				}
			}
		}

		if (current->length == 0)
			continue;

		write_record(output_file, TYPE_INPUT, current->delay, current->min_delay, (unsigned char *) current->string, current->length);
		/* Resync timestamp */
		init_timestamp();
		copy_attrs_to_terminal(master);
		safe_write(master, current->string, current->length);
	}
}

int tdrerecord_main(int argc, char *argv[]) {
	int slave;
	int status;
	char *cwd_buffer;

	parse_options(argc, argv);

	if (!isatty(STDIN_FILENO))
		fatal("Can only rerecord from a terminal devices\n");

	reset_lexer(input);
	parse();

	output_file = open_output(&output, directory);

	fprintf(output_file, "# Recorded with working directory %s\n", cwd_buffer = getcwd_wrapper());
	free(cwd_buffer);

	resize_capable = detect_resize_capable();

	init_timestamp();

	install_signal_handler(SIGWINCH, sigwinch_handler, "SIGWINCH");
	/* Get terminal attributes. */
	save_tty();
	install_signal_handler(SIGCHLD, sigchld_handler, "SIGCHLD");

	/* Unset the variables saved in the recording. */
	unsetenv("TERM");
	unsetenv("LINES");
	unsetenv("COLUMS");
	unsetenv("LANG");
	unsetenv("LC_CTYPE");

	if (port_openpty(&master, &slave, NULL) < 0)
		fatal("Error opening pty: %s\n", strerror(errno));

	set_non_block(STDIN_FILENO, "terminal", td_true);
	set_non_block(master, "pty", td_true);
	set_non_block(signal_pipe[PIPE_READ], "pipe", td_true);

	while (script != NULL) {
		switch (script->type) {
			case EXP_START: {
				StringListNode *ptr;
				fprintf(output_file, "start");
				ptr = script->un.args;
				while (ptr != NULL) {
					fputc(' ', output_file);
					write_escaped_string(output_file, ptr->string, strlen(ptr->string));
					ptr = ptr->next;
				}
				fprintf(output_file, "\n");

				pid = start_client(script, slave, NULL);
				break;
			}
			case EXP_EXPECT:
			case EXP_EXPECT_SUSPEND:
				/* IGNORE */
				break;
			case EXP_SEND:
				send_keys(script);
				break;
			case EXP_EXPECT_EXIT:
			case EXP_INTERACT:
				copy_attrs_to_terminal(master);
				status = interact_loop(master, pid, output_file, -1);
				fclose(output_file);

				reset_tty();
				fprintf(stderr, "-- recording is saved in %s --\n", output);
				exit(WEXITSTATUS(status));
				break;
			case EXP_WINDOW_SIZE:
				set_window_size(script);
				break;
			case EXP_ENV:
				fprintf(output_file, "env \"%s\" ", script->un.args->string);
				write_escaped_string(output_file, script->un.args->next->string, strlen(script->un.args->next->string));
				fputc('\n', output_file);
				setenv(script->un.args->string, script->un.args->next->string, 0);
				break;
			case EXP_REQUIRE_VERSION:
				fprintf(output_file, "require_version %d\n", script->un.number);
				break;
			default:
				fatal("Internal error\n");
		}
		script = script->next;
	}
	return EXIT_SUCCESS;
}
