/* Copyright (C) 2010,2012 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 <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <termios.h>

#include "optionMacros.h"
#include "common.h"

/* TODO:
- if we want to allow interact in replay, we may well best integrate replay and record in one program,
  or split out common code
- we could try using TIOCPKT to see whether that could solve our problems with
  wrong input modes (see tty_ioctl)
- should we try to copy tcattrs between consequtive reads/writes from/to pty?
*/

static char *output, *environment;
static const char *directory;
static int prog_start_index = -1;
static FILE *output_file;
static int allow_x11;

static void printUsage(void) {
	printf("Usage: tdrecord [OPTIONS] <client> [<client options>]\n");
	printf("  -d<dir>,--directory=<dir>      Save recording in directory <dir>\n");
	printf("  -e<vars>,--environment=<vars>  Save environment variables <vars>\n");
	printf("  -o<file>,--output=<file>       Save recording as <file>\n");
	printf("  -V, --version                  Print version and copyright information\n");
	printf("  -X, --allow-x11                Don't clear the DISPLAY environment variable\n");
	printf("                                   (allows communication with X11)\n");
	exit(EXIT_SUCCESS);
}


static PARSE_FUNCTION(parse_options)
	OPTIONS
		OPTION('d', "directory", REQUIRED_ARG)
			directory = optArg;
		END_OPTION
		OPTION('e', "environment", REQUIRED_ARG)
			environment = optArg;
		END_OPTION
		OPTION('o', "output", REQUIRED_ARG)
			output = optArg;
		END_OPTION
		OPTION('h', "help", NO_ARG)
			printUsage();
		END_OPTION
		OPTION('V', "version", NO_ARG)
			fputs("tdrecord " VERSION_STRING "\nCopyright (C) 2010,2012 G.P. Halkes\nLicensed under the GNU General Public License version 3\n", stdout); /* @copyright */
			exit(0);
		END_OPTION
		OPTION('X', "allow-x11", NO_ARG)
			allow_x11 = 1;
		END_OPTION
		DOUBLE_DASH
			NO_MORE_OPTIONS;
		END_OPTION

		fatal("Unknown option " OPTFMT "\n", OPTPRARG);
	NO_OPTION
		NO_MORE_OPTIONS;
		if (prog_start_index < 0)
			prog_start_index = optargind;
	END_OPTIONS
END_FUNCTION

static void save_env(const char *var) {
	const char *value = getenv(var);
	if (value != NULL) {
		fprintf(output_file, "env \"%s\" ", var);
		write_escaped_string(output_file, value, strlen(value));
		fputc('\n', output_file);
	}
}

int tdrecord_main(int argc, char *argv[]) {
	struct winsize wsz, *wsz_setting;
	int master, status, i;
	char *cwd_buffer;
	pid_t pid;

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

	parse_options(argc, argv);
	if (prog_start_index < 0)
		fatal("No program specified\n");

	output_file = open_output(&output, directory);

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

	save_env("TERM");
	save_env("LINES");
	save_env("COLUMS");
	save_env("LANG");
	save_env("LC_CTYPE");

	if (environment != NULL) {
		char *var;
		for (var = strtok(environment, ","); var != NULL; var = strtok(NULL, ","))
			save_env(var);
	}

	init_timestamp();

	install_signal_handler(SIGWINCH, sigwinch_handler, "SIGWINCH");
	install_signal_handler(SIGCHLD, sigchld_handler, "SIGCHLD");

	/* Get terminal size. */
	if (ioctl(STDIN_FILENO, TIOCGWINSZ, &wsz) < 0) {
		fprintf(stderr, "Warning: could not obtain window size: %s\n", strerror(errno));
		wsz_setting = NULL;
	} else {
		fprintf(output_file, "window_size %d %d\n", wsz.ws_col, wsz.ws_row);
		wsz_setting = &wsz;
	}

	/* Write the program and its arguments to the recording */
	fputs("start", output_file);
	for (i = prog_start_index; i < argc; i++) {
		fputc(' ', output_file);
		write_escaped_string(output_file, argv[i], strlen(argv[i]));
	}
	fputc('\n', output_file);

	if ((pid = port_forkpty(&master, wsz_setting)) < 0)
		fatal("forkpty failed: %s\n", strerror(errno));

	if (pid == 0) {
		/* Slave side: start proces */

		if (!allow_x11)
			/* Don't want program to communicate with X11 server for modifier states. */
			unsetenv("DISPLAY");

		execvp(argv[prog_start_index], argv + prog_start_index);
		unlink(output);
		fatal("Error executing process: %s\n", strerror(errno));
	}

	save_tty();

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

	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));
}
