/***************************************************************************
* $Id: mondoarchive.c 1977 2008-06-02 08:49:01Z bruno $
*/


/**
 * @file
 * The main file for mondoarchive.
 */

/************************* #include statements *************************/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <locale.h>

#include "mr_gettext.h"
#include "mondoarchive.h"
#include "mr_mem.h"
#include "mr_str.h"
#include "mr_msg.h"
#include "mr_file.h"
#include "mr_err.h"
#include "mr_conf.h"

#include "my-stuff.h"
#include "mondostructures.h"
#include "libmondo.h"
#include "mondo-cli-EXT.h"

// for CVS
//static char cvsid[] = "$Id: mondoarchive.c 1977 2008-06-02 08:49:01Z bruno $";

/************************* external variables *************************/
extern void set_signals(int);
extern int g_current_media_number;
extern void register_pid(pid_t, char *);
extern int g_currentY;
extern bool g_text_mode;
extern char *g_boot_mountpt;
extern bool g_remount_cdrom_at_end, g_remount_floppy_at_end;
extern char *g_cdrw_drive_is_here;
extern double g_kernel_version;
extern char *g_magicdev_command;
extern t_bkptype g_backup_media_type;

extern char *get_uname_m(void);

static char *g_cdrom_drive_is_here = NULL;
static char *g_dvd_drive_is_here = NULL;

struct mr_ar_conf *mr_conf = NULL;

/***************** global vars ******************/
long diffs;

/****************** subroutines used only here ******************/

/**
 * Whether we're restoring from ISOs. Obviously not, since this is the
 * backup program.
 * @note You @b MUST declare this variable somewhere in your program if
 * you use libmondo. Otherwise the link will fail.
 * @ingroup globalGroup
 */
bool g_ISO_restore_mode = FALSE;

/* Do we use extended attributes and acl ?
 *  * By default no, use --acl & --attr options to force their usage */
char *g_getfacl = NULL;
char *g_getfattr = NULL;

/* Reference to global bkpinfo */
struct s_bkpinfo *bkpinfo;

/****************** subroutines used only by main.c ******************/

/**
 * Print a "don't panic" message to the log and a message about the logfile to the screen.
 */
static void welcome_to_mondoarchive(void)
{
	char *tmp = NULL;

	mr_msg(0, "Mondo Archive v%s --- http://www.mondorescue.org", PACKAGE_VERSION);
	mr_msg(0, "running %s binaries", get_architecture());
	tmp = get_uname_m();
	mr_msg(0, "running on %s architecture", tmp);
	mr_free(tmp);
	mr_msg(0, "-----------------------------------------------------------");
	mr_msg(0, "NB: Mondo logs almost everything, so don't panic if you see");
	mr_msg(0, "some error messages.  Please read them carefully before you");
	mr_msg(0, "decide to break out in a cold sweat.    Despite (or perhaps");
	mr_msg(0, "because of) the wealth of messages. some users are inclined");
	mr_msg(0, "to stop reading this log. If Mondo stopped for some reason,");
	mr_msg(0, "chances are it's detailed here.  More than likely there's a");
	mr_msg(0, "message at the very end of this log that will tell you what");
	mr_msg(0, "is wrong. Please read it!                          -Devteam");
	mr_msg(0, "-----------------------------------------------------------");

	mr_msg(0, "Zero...");
	mr_msg(1, "One...");
	mr_msg(2, "Two...");
	mr_msg(3, "Three...");
	mr_msg(4, "Four...");
	mr_msg(5, "Five...");
	mr_msg(6, "Six...");
	mr_msg(7, "Seven...");
	mr_msg(8, "Eight...");
	printf(_("See %s for details of backup run.\n"), MONDO_LOGFILE);
}

/**
 * Do whatever is necessary to insure a successful backup on the Linux distribution
 * of the day.
 */
static void distro_specific_kludges_at_start_of_mondoarchive(void)
{
	mr_msg(2, "Unmounting old ramdisks if necessary");
	stop_magicdev_if_necessary();	// for RH+Gnome users
	run_program_and_log_output
		("umount `mount | grep shm | grep mondo | cut -d' ' -f3`", 2);
	unmount_supermounts_if_necessary();	// for Mandrake users whose CD-ROMs are supermounted
	mount_boot_if_necessary();	// for Gentoo users with non-mounted /boot partitions
	clean_up_KDE_desktop_if_necessary();	// delete various misc ~/.* files that get in the way
}


/**
 * Undo whatever was done by distro_specific_kludges_at_start_of_mondoarchive().
 */
static void distro_specific_kludges_at_end_of_mondoarchive(void)
{
	mr_msg(2, "Restarting magicdev if necessary");
	sync();
	restart_magicdev_if_necessary();	// for RH+Gnome users

	mr_msg(2, "Restarting supermounts if necessary");
	sync();
	remount_supermounts_if_necessary();	// for Mandrake users

	mr_msg(2, "Unmounting /boot if necessary");
	sync();
	unmount_boot_if_necessary();	// for Gentoo users
}

/* reset/empty the mr_ar_conf structure from mondo's conf file */
static void mr_ar_reset_conf(struct mr_ar_conf *mr_cnf) {

	/* This should correspond to the default conf file */
	/* Especially for boolean values */
	mr_cnf->iso_creation_cmd = NULL;
	mr_cnf->iso_creation_opt = NULL;
	mr_cnf->iso_burning_cmd = NULL;
	mr_cnf->iso_burning_opt = NULL;
	mr_cnf->iso_burning_dev = NULL;
	mr_cnf->iso_burning_speed = 0;
	mr_cnf->media_size = 0;
	mr_cnf->media_device = NULL;
	mr_cnf->iso_burning_dev = NULL;
	mr_cnf->manual_tray = FALSE;
	mr_cnf->log_level = 0;
	mr_cnf->prefix = NULL;
	mr_cnf->external_tape_blocksize = 0;
	mr_cnf->internal_tape_blocksize = 0;
	mr_cnf->kernel = NULL;
	mr_cnf->additional_modules = NULL;
	mr_cnf->boot_loader = NULL;
	mr_cnf->differential = FALSE;
	mr_cnf->compression_tool = NULL;
	mr_cnf->compression_level = 0;
	mr_cnf->exclude_paths = NULL;
	mr_cnf->include_paths = NULL;
	mr_cnf->ui_mode = NULL;
	mr_cnf->automatic_restore = FALSE;
	mr_cnf->scratch_dir = NULL;
	mr_cnf->tmp_dir = NULL;
	mr_cnf->images_dir = NULL;
}

/* fill the mr_ar_conf structure from mindi's conf file */
static void mr_ar_store_conf_mindi(struct mr_ar_conf *mr_cnf) {
	
	char *p = NULL;

	p = mr_conf_sread("mr_iso_creation_cmd");
	if (p != NULL) {
		mr_cnf->iso_creation_cmd = p;
	}
	p = mr_conf_sread("mr_iso_creation_opt");
	if (p != NULL) {
		mr_cnf->iso_creation_opt = p;
	}
}

/* create the mr_ar_conf structure from mondo's conf file */
static void mr_ar_store_conf(struct mr_ar_conf *mr_cnf) {
	
	char *p = NULL;

	p = mr_conf_sread("mondo_iso_burning_cmd");
	if (p != NULL) {
		mr_cnf->iso_burning_cmd = p;
	}

	p = mr_conf_sread("mondo_iso_burning_opt");
	if (p != NULL) {
		mr_cnf->iso_burning_opt = p;
	}

	p = mr_conf_sread("mondo_iso_burning_dev");
	if (p != NULL) {
		mr_cnf->iso_burning_dev = p;
	}

	p = mr_conf_iread("mondo_iso_burning_speed");
	if (p != NULL ) {
		mr_cnf->iso_burning_speed = atoi(p);
		mr_free(p);
	}

	p = mr_conf_iread("mondo_media_size");
	if (p != NULL ) {
		mr_cnf->media_size = atoi(p);
		mr_free(p);
	}

	p = mr_conf_sread("mondo_media_device");
	if (p != NULL) {
		mr_cnf->media_device = p;
	}
	/* If no specific device name for the burning command (a la ATAPI:0,0,0), 
	 * then use the normal device name (a la /dev/hda) */
	if ((mr_cnf->iso_burning_dev == NULL) && (mr_cnf->media_device != NULL)) {
		mr_asprintf(&p, mr_cnf->media_device);
		mr_cnf->iso_burning_dev = p;
	}

	p = mr_conf_bread("mondo_manual_tray");
	if (p != NULL) {
		mr_cnf->manual_tray = mr_atob(p);
		mr_free(p);
	}

	p = mr_conf_iread("mondo_log_level");
	if (p != NULL) {
		mr_cnf->log_level = atoi(p);
		mr_free(p);
	}

	p = mr_conf_sread("mondo_prefix");
	if (p != NULL) {
		mr_cnf->prefix = p;
	}

	p = mr_conf_iread("mondo_external_tape_blocksize");
	if (p != NULL) {
		mr_cnf->external_tape_blocksize = atoi(p);
		mr_free(p);
	}

	p = mr_conf_iread("mondo_internal_tape_blocksize");
	if (p != NULL) {
		mr_cnf->internal_tape_blocksize = atoi(p);
		mr_free(p);
	}

	p = mr_conf_sread("mondo_kernel");
	if (p != NULL) {
		mr_cnf->kernel = p;
	}

	p = mr_conf_sread("mondo_additional_modules");
	if (p != NULL) {
		mr_cnf->additional_modules = p;
	}

	p = mr_conf_sread("mondo_boot_loader");
	if (p != NULL) {
		mr_cnf->boot_loader = p;
	}

	p = mr_conf_bread("mondo_differential");
	if (p != NULL) {
		mr_cnf->differential = mr_atob(p);
		mr_free(p);
	}

	p = mr_conf_sread("mondo_compression_tool");
	if (p != NULL) {
		mr_cnf->compression_tool = p;
	}

	p = mr_conf_sread("mondo_compression_suffix");
	if (p != NULL) {
		mr_cnf->compression_suffix = p;
	}

	p = mr_conf_iread("mondo_compression_level");
	if (p != NULL) {
		mr_cnf->compression_level = atoi(p);
		mr_free(p);
	}

	p = mr_conf_sread("mondo_exclude_paths");
	if (p != NULL) {
		mr_cnf->exclude_paths = p;
	}

	p = mr_conf_sread("mondo_include_paths");
	if (p != NULL) {
		mr_cnf->include_paths = p;
	}

	p = mr_conf_sread("mondo_ui_mode");
	if (p != NULL) {
		mr_cnf->ui_mode = p;
	}

	p = mr_conf_bread("mondo_automatic_restore");
	if (p != NULL) {
		mr_cnf->automatic_restore = mr_atob(p);
		mr_free(p);
	}

	p = mr_conf_sread("mondo_scratch_dir");
	if (p != NULL) {
		mr_cnf->scratch_dir = p;
	}

	p = mr_conf_sread("mondo_tmp_dir");
	if (p != NULL) {
		mr_cnf->tmp_dir = p;
	}

	p = mr_conf_sread("mondo_images_dir");
	if (p != NULL) {
		mr_cnf->images_dir = p;
	}
	mr_msg(5, "Directory for images is %s", mr_cnf->images_dir);
}

/* destroy the mr_ar_conf structure's content */
static void mr_ar_clean_conf(struct mr_ar_conf *mr_cnf) {
	
	if (mr_cnf == NULL) {
		return;
	}
	mr_free(mr_cnf->iso_creation_cmd);
	mr_free(mr_cnf->iso_creation_opt);
	mr_free(mr_cnf->iso_burning_cmd);
	mr_free(mr_cnf->iso_burning_dev);
	mr_free(mr_cnf->iso_burning_opt);
	mr_free(mr_cnf->media_device);
	mr_free(mr_cnf->prefix);
	mr_free(mr_cnf->kernel);
	mr_free(mr_cnf->additional_modules);
	mr_free(mr_cnf->boot_loader);
	mr_free(mr_cnf->compression_tool);
	mr_free(mr_cnf->exclude_paths);
	mr_free(mr_cnf->include_paths);
	mr_free(mr_cnf->ui_mode);
	mr_free(mr_cnf->scratch_dir);
	mr_free(mr_cnf->tmp_dir);
	mr_free(mr_cnf->images_dir);
	mr_free(mr_cnf);
}

/* Create the pointer to the function called in mr_exit */
void (*mr_cleanup)(void) = NULL;

/* Just for init */
void mr_ar_cleanup_empty(void) {
}

/* Cleanup all memory allocated in various structures */
void mr_ar_cleanup(void) {
	/* Highly incomplete function for the moment */
	/* We have to free all allocated memory */
	mr_ar_clean_conf(mr_conf);
	/* We have to remove all temporary files */
	/* We have to unmount what has been mounted */
	/* We have to properly end newt */
	/* We have to remind people of log files */

	mr_msg_close();
}

/*-----------------------------------------------------------*/



/**
 * Backup/verify the user's data.
 * What did you think it did, anyway? :-)
 */
int main(int argc, char *argv[])
{
	struct stat stbuf;
	char *tmp = NULL;
	int res = 0;
	int retval = 0;
	char *say_at_end = NULL;
	char *say_at_end2 = NULL;

#ifdef ENABLE_NLS
	setlocale(LC_ALL, "");
	(void) textdomain("mondo");
#endif
	printf(_("Initializing...\n"));

	bkpinfo = mr_malloc(sizeof(struct s_bkpinfo));
	reset_bkpinfo();

	/* Reference a dummy cleanup function for mr_exit temporarily */
	mr_cleanup = &mr_ar_cleanup_empty;

	/* initialize log file with time stamp */
	/* We start with a loglevel of 4 - Adapted later on */
	/* It's mandatory to set this up first as all mr_ functions rely on it */
	unlink(MONDO_LOGFILE);
	mr_msg_init(MONDO_LOGFILE,4);
	mr_msg(0, _("Time started: %s"), mr_date());

	/* Make sure I'm root; abort if not */
	if (getuid() != 0) {
		mr_log_exit(127, _("Please run as root."));
	}

	/* If -V, -v or --version then echo version no. and quit */
	if (argc == 2
		&& (!strcmp(argv[argc - 1], "-v") || !strcmp(argv[argc - 1], "-V")
			|| !strcmp(argv[argc - 1], "--version"))) {
		printf(_("mondoarchive v%s\nSee man page for help\n"), PACKAGE_VERSION);
		mr_exit(0, NULL);
	}

	/* Conf file management */
	mr_conf = mr_malloc(sizeof(struct mr_ar_conf));
	mr_ar_reset_conf(mr_conf);
	/* Check md5 sum before */
	/* Get content */
	if (mr_conf_open(MONDO_CONF_DIR"/mondo.conf.dist") != 0) {
			mr_log_exit(-1, "Unable to open "MONDO_CONF_DIR"/mondo.conf.dist");
	}
	mr_ar_store_conf(mr_conf);
	/* Reference the right cleanup function for mr_exit now it's allocated */
	mr_cleanup = &mr_ar_cleanup;
	mr_conf_close();

	if (mr_conf_open(MONDO_CONF_DIR"/mondo.conf") == 0) {
		mr_ar_store_conf(mr_conf);
		mr_conf_close();
	}

	/* Check md5 sum before */
	/* Get content of mindi conf file now to finish structure initialization */
/* Tempo Hack */
#define MINDI_CONF_DIR MONDO_CONF_DIR"/../mindi"
	if (mr_conf_open(MINDI_CONF_DIR"/mindi.conf.dist") != 0) {
			mr_log_exit(-1, "Unable to open "MINDI_CONF_DIR"/mindi.conf.dist");
	}
	mr_ar_store_conf_mindi(mr_conf);
	mr_conf_close();

	if (mr_conf_open(MINDI_CONF_DIR"/mindi.conf") == 0) {
		mr_ar_store_conf_mindi(mr_conf);
		mr_conf_close();
	}
	mr_msg(5, "Command for ISO images is %s", mr_conf->iso_creation_cmd);

	/* Add MONDO_SHARE + other environment variables for mindi */
	setenv_mondo_var();

	/* Initialize variables */
	malloc_libmondo_global_strings();
	diffs = 0;
	if (stat(MONDO_CACHE, &stbuf) != 0) {
		mr_mkdir(MONDO_CACHE,0x755);
	}

	/* BERLIOS: Hardcoded to be improved */
	unlink(MONDO_CACHE"/mindi.conf");
	unlink(MONDORESTORECFG);

	/* Configure the bkpinfo structure, global file paths, etc. */
	g_main_pid = getpid();
	mr_msg(9, "This");

	register_pid(g_main_pid, "mondo");
	set_signals(TRUE);			// catch SIGTERM, etc.
	run_program_and_log_output("dmesg -n1", TRUE);

	mr_msg(9, "Next");
	make_hole_for_dir(MONDO_CACHE);

	welcome_to_mondoarchive();
	distro_specific_kludges_at_start_of_mondoarchive();
	g_kernel_version = get_kernel_version();

	if (argc == 4 && !strcmp(argv[1], "getfattr")) {
		mr_conf->log_level = 10;
		g_text_mode = TRUE;
		setup_newt_stuff();
		if (!strstr(argv[2], "filelist")) {
			mr_msg(1,_("Sorry - filelist goes first\n"));
			finish(1);
		} else {
			finish(get_fattr_list(argv[2], argv[3]));
		}
		finish(0);
	}
	if (argc == 4 && !strcmp(argv[1], "setfattr")) {
		mr_conf->log_level = 10;
		g_text_mode = TRUE;
		setup_newt_stuff();
		finish(set_fattr_list(argv[2], argv[3]));
	}

	if (argc == 3 && !strcmp(argv[1], "wildcards")) {
		mr_conf->log_level = 10;
		g_text_mode = TRUE;
		setup_newt_stuff();
		tmp = mr_stresc(argv[2], WILDCHARS, BACKSLASH);
		printf("in=%s; out=%s\n", argv[2], tmp);
		mr_free(tmp);
		finish(1);
	}

	if (argc == 4 && !strcmp(argv[1], "getfacl")) {
		mr_conf->log_level = 10;
		g_text_mode = TRUE;
		setup_newt_stuff();
		if (!strstr(argv[2], "filelist")) {
			mr_msg(1,_("Sorry - filelist goes first\n"));
			finish(1);
		} else {
			finish(get_acl_list(argv[2], argv[3]));
		}
		finish(0);
	}
	if (argc == 4 && !strcmp(argv[1], "setfacl")) {
		mr_conf->log_level = 10;
		g_text_mode = TRUE;
		setup_newt_stuff();
		finish(set_acl_list(argv[2], argv[3]));
	}

	if (argc > 2 && !strcmp(argv[1], "find-cd")) {
		mr_conf->log_level = 10;
		g_text_mode = TRUE;
		setup_newt_stuff();
		malloc_string(tmp);
		if (find_cdrw_device(tmp)) {
			mr_msg(1,_("Failed to find CDR-RW drive\n"));
		} else {
			mr_msg(1,_("CD-RW is at %s\n"), tmp);
		}
		tmp[0] = '\0';
		if (find_cdrom_device(tmp, atoi(argv[2]))) {
			mr_msg(1,_("Failed to find CD-ROM drive\n"));
		} else {
			mr_msg(1,_("CD-ROM is at %s\n"), tmp);
		}
		mr_free(tmp);
		finish(0);
	}

	if (argc > 2 && !strcmp(argv[1], "find-dvd")) {
		mr_conf->log_level = 10;
		g_text_mode = TRUE;
		setup_newt_stuff();
		malloc_string(tmp);
		if (find_dvd_device(tmp, atoi(argv[2]))) {
			mr_msg(1,_("Failed to find DVD drive\n"));
		} else {
			mr_msg(1,_("DVD is at %s\n"), tmp);
		}
		mr_free(tmp);
		finish(0);
	}

	if (argc > 2 && !strcmp(argv[1], "disksize")) {
		printf("%s --> %ld\n", argv[2], get_phys_size_of_drive(argv[2]));
		finish(0);
	}
	if (argc > 2 && !strcmp(argv[1], "test-dev")) {
		if (is_dev_an_NTFS_dev(argv[2])) {
			mr_msg(1,_("%s is indeed an NTFS dev\n"), argv[2]);
		} else {
			mr_msg(1,_("%s is _not_ an NTFS dev\n"), argv[2]);
		}
		finish(0);
	}

	if (pre_param_configuration()) {
		fatal_error
			("Pre-param initialization phase failed. Please review the error messages above, make the specified changes, then try again. Exiting...");
	}
	sprintf(g_erase_tmpdir_and_scratchdir, "rm -Rf %s %s", bkpinfo->tmpdir,
			bkpinfo->scratchdir);

	/* Process command line, if there is one. If not, ask user for info. */
	if (argc == 1) {
		g_text_mode = FALSE;
		setup_newt_stuff();
		res = interactively_obtain_media_parameters_from_user(TRUE);	/* yes, archiving */
		if (res) {
			fatal_error
				("Syntax error. Please review the parameters you have supplied and try again.");
		}
	} else {
		res = handle_incoming_parameters(argc, argv);
		if (res) {
			mr_msg(1,
				_("Errors were detected in the command line you supplied.\n"));
			mr_msg(1,_("Please review the log file - %s \n"),MONDO_LOGFILE);
			mr_msg(1, "Mondoarchive will now exit.");
			finish(1);
		}
		setup_newt_stuff();
	}

/* Finish configuring global structures */
	if (post_param_configuration()) {
		fatal_error
			("Post-param initialization phase failed. Perhaps bad parameters were supplied to mondoarchive? Please review the documentation, error messages and logs. Exiting...");
	}

	log_to_screen
		(_("BusyBox's sources are available from http://www.busybox.net"));


	/* If we're meant to backup then backup */
	if (bkpinfo->backup_data) {
		res = backup_data();
		retval += res;
		if (res) {
			mr_strcat(say_at_end,
				   _("Data archived. Please check the logs, just as a precaution. "));
		} else {
			mr_strcat(say_at_end, _("Data archived OK. "));
		}
	}

	/* If we're meant to verify then verify */
	if (bkpinfo->verify_data) {
		res = verify_data();
		if (res < 0) {
			mr_asprintf(&say_at_end2, _("%d difference%c found."), -res,
					(-res != 1) ? 's' : ' ');
			res = 0;
		}
		retval += res;
	}

	/* Report result of entire operation (success? errors?) */
	if (!retval) {
		mvaddstr_and_log_it(g_currentY++, 0,
							_("Backup and/or verify ran to completion. Everything appears to be fine."));
	} else {
		mvaddstr_and_log_it(g_currentY++, 0,
							_("Backup and/or verify ran to completion. However, errors did occur."));
	}

	if (does_file_exist(MINDI_CACHE"/mondorescue.iso")) {
		log_to_screen
			(_(MINDI_CACHE"/mondorescue.iso, a boot/utility CD, is available if you want it."));
	}

	if (length_of_file(MONDO_CACHE"/changed.files") > 2) {
		if (g_text_mode) {
			log_to_screen
				(_("Type 'less "MONDO_CACHE"/changed.files' to see which files don't match the archives"));
		} else {
			mr_msg(1,
					_("Type 'less "MONDO_CACHE"/changed.files' to see which files don't match the archives"));
			mr_msg(2, "Calling popup_changelist_from_file()");
			popup_changelist_from_file(MONDO_CACHE"/changed.files");
			mr_msg(2, "Returned from popup_changelist_from_file()");
		}
	} else {
		unlink(MONDO_CACHE"/changed.files");
	}
	log_to_screen(say_at_end);
	mr_free(say_at_end);
	if (say_at_end2 != NULL) {
		log_to_screen(say_at_end2);
		mr_free(say_at_end2);
	}

	mr_asprintf(&tmp, "umount %s/tmpfs", bkpinfo->tmpdir);
	run_program_and_log_output(tmp, TRUE);
	mr_free(tmp);
	if (bkpinfo->backup_media_type == usb) {
		log_msg(1, "Unmounting USB device.");
		mr_asprintf(&tmp, "umount %s1", bkpinfo->media_device);
		run_program_and_log_output(tmp, TRUE);
		mr_free(tmp);
	}

	run_program_and_log_output("mount", 2);

	system("rm -f "MONDO_CACHE"/last-backup.aborted");
	if (!retval) {
		printf(_("Mondoarchive ran OK.\n"));
	} else {
		printf(_("Errors occurred during backup. Please check logfile.\n"));
	}
	distro_specific_kludges_at_end_of_mondoarchive();
	register_pid(0, "mondo");
	set_signals(FALSE);

	free_libmondo_global_strings();
	mr_free(bkpinfo);

	if (!g_cdrom_drive_is_here) {
		mr_msg(10, "FYI, g_cdrom_drive_is_here was never used");
	}
	if (!g_dvd_drive_is_here) {
		mr_msg(10, "FYI, g_dvd_drive_is_here was never used");
	}

	/* finalize log file with time stamp */
	mr_msg(1, "Time finished: %s", mr_date());
	mr_msg_close();

	chdir("/tmp");

	if (!g_text_mode) {
		popup_and_OK
			(_("Mondo Archive has finished its run. Please press ENTER to return to the shell prompt."));
		log_to_screen(_("See %s for details of backup run."), MONDO_LOGFILE);
	} else {
		printf(_("See %s for details of backup run.\n"), MONDO_LOGFILE);
		mr_exit(retval, NULL);
	}
	finish(retval);

	return EXIT_SUCCESS;
}
=======
/***************************************************************************
                          main.c  -  description
                             -------------------
    begin                : Fri Apr 19 16:40:35 EDT 2002
    copyright            : (C) 2002 by Stan Benoit
    email                : troff@nakedsoul.org
    cvsid                : $Id: mondoarchive.c 1977 2008-06-02 08:49:01Z bruno $
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

/**
 * @file
 * The main file for mondoarchive.
 */

/************************* #include statements *************************/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include "my-stuff.h"
#include "../common/mondostructures.h"
#include "../common/libmondo.h"
#include "../common/libmondo-cli-EXT.h"
#include "../common/libmondo-tools-EXT.h"
#include "mondoarchive.h"

// for CVS
//static char cvsid[] = "$Id: mondoarchive.c 1977 2008-06-02 08:49:01Z bruno $";

/************************* external variables *************************/
extern void set_signals(int);
extern int g_current_media_number;
extern void register_pid(pid_t, char *);
extern int g_currentY;
extern bool g_text_mode;
extern char *g_boot_mountpt;
extern bool g_remount_floppy_at_end;
extern char *g_cdrw_drive_is_here;
static char *g_cdrom_drive_is_here = NULL;
static char *g_dvd_drive_is_here = NULL;
extern double g_kernel_version;

/***************** global vars, used only by main.c ******************/
long diffs;

extern t_bkptype g_backup_media_type;
extern int g_loglevel;

/**
 * Whether we're restoring from ISOs. Obviously not, since this is the
 * backup program.
 * @note You @b MUST declare this variable somewhere in your program if
 * you use libmondo. Otherwise the link will fail.
 * @ingroup globalGroup
 */
bool g_ISO_restore_mode = FALSE;

/* Do we use extended attributes and acl ?
 *  * By default no, use --acl & --attr options to force their usage */
char *g_getfacl = NULL;
char *g_getfattr = NULL;

/* Reference to global bkpinfo */
struct s_bkpinfo *bkpinfo;

/* To be coded */
void free_MR_global_filenames(void) {
}

/****************** subroutines used only by main.c ******************/


/**
 * Print a "don't panic" message to the log and a message about the logfile to the screen.
 */
void welcome_to_mondoarchive(void)
{
	char *tmp = NULL;

	log_msg(0, "Mondo Archive v%s --- http://www.mondorescue.org",
			PACKAGE_VERSION);
	log_msg(0, "running %s binaries", get_architecture());
	tmp = get_uname_m();
	log_msg(0, "running on %s architecture", tmp);
	free(tmp);
	log_msg(0,
			"-----------------------------------------------------------");
	log_msg(0,
			"NB: Mondo logs almost everything, so don't panic if you see");
	log_msg(0,
			"some error messages.  Please read them carefully before you");
	log_msg(0,
			"decide to break out in a cold sweat.    Despite (or perhaps");
	log_msg(0,
			"because of) the wealth of messages. some users are inclined");
	log_msg(0,
			"to stop reading this log. If Mondo stopped for some reason,");
	log_msg(0,
			"chances are it's detailed here.  More than likely there's a");
	log_msg(0,
			"message at the very end of this log that will tell you what");
	log_msg(0,
			"is wrong. Please read it!                          -Devteam");
	log_msg(0,
			"-----------------------------------------------------------");

	log_msg(0, "Zero...");
	log_msg(1, "One...");
	log_msg(2, "Two...");
	log_msg(3, "Three...");
	log_msg(4, "Four...");
	log_msg(5, "Five...");
	log_msg(6, "Six...");
	log_msg(7, "Seven...");
	log_msg(8, "Eight...");
	printf("See %s for details of backup run.\n", MONDO_LOGFILE);
}


extern char *g_magicdev_command;

/**
 * Do whatever is necessary to insure a successful backup on the Linux distribution
 * of the day.
 */
void distro_specific_kludges_at_start_of_mondoarchive(void)
{
	log_msg(2, "Unmounting old ramdisks if necessary");
	stop_magicdev_if_necessary();	// for RH+Gnome users
	run_program_and_log_output
		("umount `mount | grep shm | grep mondo | cut -d' ' -f3`", 2);
	unmount_supermounts_if_necessary();	// for Mandrake users whose CD-ROMs are supermounted
	//  stop_autofs_if_necessary(); // for Xandros users
	mount_boot_if_necessary();	// for Gentoo users with non-mounted /boot partitions
	clean_up_KDE_desktop_if_necessary();	// delete various misc ~/.* files that get in the way
}



/**
 * Undo whatever was done by distro_specific_kludges_at_start_of_mondoarchive().
 */
void distro_specific_kludges_at_end_of_mondoarchive(void)
{
//  char tmp[500];
	log_msg(2, "Restarting magicdev if necessary");
	sync();
	restart_magicdev_if_necessary();	// for RH+Gnome users

	log_msg(2, "Restarting autofs if necessary");
	sync();
	//  restart_autofs_if_necessary(); // for Xandros users

	log_msg(2, "Restarting supermounts if necessary");
	sync();
	remount_supermounts_if_necessary();	// for Mandrake users

	log_msg(2, "Unmounting /boot if necessary");
	sync();
	unmount_boot_if_necessary();	// for Gentoo users

//  log_msg( 2, "Cleaning up KDE desktop");
//  clean_up_KDE_desktop_if_necessary();
}


/**
 * Backup/verify the user's data.
 * What did you think it did, anyway? :-)
 */
int main(int argc, char *argv[])
{
	char *tmp;
	int res, retval;
	char *say_at_end;

/* Make sure I'm root; abort if not */
	if (getuid() != 0) {
		fprintf(stderr, "Please run as root.\r\n");
		exit(127);
	}

/* If -V, -v or --version then echo version no. and quit */
	if (argc == 2
		&& (!strcmp(argv[argc - 1], "-v") || !strcmp(argv[argc - 1], "-V")
			|| !strcmp(argv[argc - 1], "--version"))) {
		printf("mondoarchive v%s\nSee man page for help\n", PACKAGE_VERSION);
		exit(0);
	}

/* Initialize variables */

	printf("Initializing...\n");
	if (!(bkpinfo = malloc(sizeof(struct s_bkpinfo)))) {
		fatal_error("Cannot malloc bkpinfo");
	}
	reset_bkpinfo();

	res = 0;
	retval = 0;
	diffs = 0;
	malloc_string(tmp);
	malloc_string(say_at_end);
	say_at_end[0] = '\0';
	malloc_libmondo_global_strings();

	/* initialize log file with time stamp */
	unlink(MONDO_LOGFILE);
	log_msg(0, "Time started: %s", mr_date());

	/* make sure PATH environmental variable allows access to mkfs, fdisk, etc. */
	strncpy(tmp, getenv("PATH"), MAX_STR_LEN - 1);
	tmp[MAX_STR_LEN - 1] = '\0';
	if (strlen(tmp) >= MAX_STR_LEN - 33) {
		fatal_error
			("Your PATH environmental variable is too long. Please shorten it.");
	}
	strcat(tmp, ":/sbin:/usr/sbin:/usr/local/sbin");
	setenv("PATH", tmp, 1);

	/* Add the ARCH environment variable for ia64 purposes */
	strncpy(tmp, get_architecture(), MAX_STR_LEN - 1);
	tmp[MAX_STR_LEN - 1] = '\0';
	setenv("ARCH", tmp, 1);

	/* Add MONDO_SHARE environment variable for mindi */
	setenv_mondo_share();

	/* Configure the bkpinfo structure, global file paths, etc. */
	g_main_pid = getpid();
	log_msg(9, "This");

	register_pid(g_main_pid, "mondo");
	set_signals(TRUE);			// catch SIGTERM, etc.
	run_program_and_log_output("dmesg -n1", TRUE);

	log_msg(9, "Next");
	make_hole_for_dir(MONDO_CACHE);

	welcome_to_mondoarchive();
	distro_specific_kludges_at_start_of_mondoarchive();
	g_kernel_version = get_kernel_version();

	if (argc == 4 && !strcmp(argv[1], "getfattr")) {
		g_loglevel = 10;
		g_text_mode = TRUE;
		setup_newt_stuff();
		if (!strstr(argv[2], "filelist")) {
			printf("Sorry - filelist goes first\n");
			finish(1);
		} else {
			finish(get_fattr_list(argv[2], argv[3]));
		}
		finish(0);
	}
	if (argc == 4 && !strcmp(argv[1], "setfattr")) {
		g_loglevel = 10;
//      chdir("/tmp");
		g_text_mode = TRUE;
		setup_newt_stuff();
		finish(set_fattr_list(argv[2], argv[3]));
	}

	if (argc == 3 && !strcmp(argv[1], "wildcards")) {
		g_loglevel = 10;
		g_text_mode = TRUE;
		setup_newt_stuff();
		turn_wildcard_chars_into_literal_chars(tmp, argv[2]);
		printf("in=%s; out=%s\n", argv[2], tmp);
		finish(1);
	}

	if (argc == 4 && !strcmp(argv[1], "getfacl")) {
		g_loglevel = 10;
		g_text_mode = TRUE;
		setup_newt_stuff();
		if (!strstr(argv[2], "filelist")) {
			printf("Sorry - filelist goes first\n");
			finish(1);
		} else {
			finish(get_acl_list(argv[2], argv[3]));
		}
		finish(0);
	}
	if (argc == 4 && !strcmp(argv[1], "setfacl")) {
		g_loglevel = 10;
//      chdir("/tmp");
		g_text_mode = TRUE;
		setup_newt_stuff();
		finish(set_acl_list(argv[2], argv[3]));
	}

	if (argc > 2 && !strcmp(argv[1], "find-cd")) {
		g_loglevel = 10;
		g_text_mode = TRUE;
		setup_newt_stuff();
		if (find_cdrw_device(tmp)) {
			printf("Failed to find CDR-RW drive\n");
		} else {
			printf("CD-RW is at %s\n", tmp);
		}
		tmp[0] = '\0';
		if (find_cdrom_device(tmp, atoi(argv[2]))) {
			printf("Failed to find CD-ROM drive\n");
		} else {
			printf("CD-ROM is at %s\n", tmp);
		}
		finish(0);
	}

	if (argc > 2 && !strcmp(argv[1], "find-dvd")) {
		g_loglevel = 10;
		g_text_mode = TRUE;
		setup_newt_stuff();
		if (find_dvd_device(tmp, atoi(argv[2]))) {
			printf("Failed to find DVD drive\n");
		} else {
			printf("DVD is at %s\n", tmp);
		}
		finish(0);
	}

	if (argc > 2 && !strcmp(argv[1], "disksize")) {
		printf("%s --> %ld\n", argv[2], get_phys_size_of_drive(argv[2]));
		finish(0);
	}
	if (argc > 2 && !strcmp(argv[1], "test-dev")) {
		if (is_dev_an_NTFS_dev(argv[2])) {
			printf("%s is indeed an NTFS dev\n", argv[2]);
		} else {
			printf("%s is _not_ an NTFS dev\n", argv[2]);
		}
		finish(0);
	}

	if (pre_param_configuration()) {
		fatal_error
			("Pre-param initialization phase failed. Please review the error messages above, make the specified changes, then try again. Exiting...");
	}

/* Process command line, if there is one. If not, ask user for info. */
	if (argc == 1) {
		g_text_mode = FALSE;
		setup_newt_stuff();
		res = interactively_obtain_media_parameters_from_user(TRUE);	/* yes, archiving */
		if (res) {
			fatal_error
				("Syntax error. Please review the parameters you have supplied and try again.");
		}
	} else {
		res = handle_incoming_parameters(argc, argv);
		if (res) {
			printf
				("Errors were detected in the command line you supplied.\n");
			printf("Please review the log file - %s\n", MONDO_LOGFILE );
			log_msg(1, "Mondoarchive will now exit.");
			finish(1);
		}
		setup_newt_stuff();
	}

/* Finish configuring global structures */
	if (post_param_configuration()) {
		fatal_error
			("Post-param initialization phase failed. Perhaps bad parameters were supplied to mondoarchive? Please review the documentation, error messages and logs. Exiting...");
	}

	log_to_screen
		("BusyBox's sources are available from http://www.busybox.net");

	/* If we're meant to backup then backup */
	if (bkpinfo->backup_data) {
		res = backup_data();
		retval += res;
		if (res) {
			strcat(say_at_end,
				   "Data archived. Please check the logs, just as a precaution. ");
		} else {
			strcat(say_at_end, "Data archived OK. ");
		}
	}

/* If we're meant to verify then verify */
	if (bkpinfo->verify_data) {
		res = verify_data();
		if (res < 0) {
			sprintf(tmp, "%d difference%c found.", -res,
					(-res != 1) ? 's' : ' ');
			strcat(say_at_end, tmp);
			log_to_screen(tmp);
			res = 0;
		}
		retval += res;
	}

/* Report result of entire operation (success? errors?) */
	if (!retval) {
		mvaddstr_and_log_it(g_currentY++, 0,
							"Backup and/or verify ran to completion. Everything appears to be fine.");
	} else {
		mvaddstr_and_log_it(g_currentY++, 0,
							"Backup and/or verify ran to completion. However, errors did occur.");
	}

	if (does_file_exist(MINDI_CACHE"/mondorescue.iso")) {
		log_to_screen
			(MINDI_CACHE"/mondorescue.iso, a boot/utility CD, is available if you want it.");
	}

	if (length_of_file(MONDO_CACHE"/changed.files") > 2) {
		if (g_text_mode) {
			log_to_screen("Type 'less "MONDO_CACHE"/changed.files' to see which files don't match the archives");
		} else {
			log_msg(1, "Type 'less "MONDO_CACHE"/changed.files' to see which files don't match the archives");
			log_msg(2, "Calling popup_changelist_from_file()");
			popup_changelist_from_file(MONDO_CACHE"/changed.files");
			log_msg(2, "Returned from popup_changelist_from_file()");
		}
	} else {
		unlink(MONDO_CACHE"/changed.files");
	}
	log_to_screen(say_at_end);
	sprintf(tmp, "umount %s/tmpfs", bkpinfo->tmpdir);
	run_program_and_log_output(tmp, TRUE);
	if (bkpinfo->backup_media_type == usb) {
		log_msg(1, "Unmounting USB device.");
		sprintf(tmp, "umount %s1", bkpinfo->media_device);
		run_program_and_log_output(tmp, TRUE);
	}

	run_program_and_log_output("mount", 2);

	system("rm -f "MONDO_CACHE"/last-backup.aborted");
	if (!retval) {
		printf("Mondoarchive ran OK.\n");
	} else {
		printf("Errors occurred during backup. Please check logfile.\n");
	}
	distro_specific_kludges_at_end_of_mondoarchive();
	register_pid(0, "mondo");
	set_signals(FALSE);

	free_libmondo_global_strings();
	paranoid_free(say_at_end);
	

	if (!g_cdrom_drive_is_here) {
		log_msg(10, "FYI, g_cdrom_drive_is_here was never used");
	}
	if (!g_dvd_drive_is_here) {
		log_msg(10, "FYI, g_dvd_drive_is_here was never used");
	}

	/* finalize log file with time stamp */
	log_msg(0, "Time finished: %s", mr_date());

	chdir("/tmp");

	if (!g_text_mode) {
		popup_and_OK
			("Mondo Archive has finished its run. Please press ENTER to return to the shell prompt.");
		log_to_screen("See %s for details of backup run.", MONDO_LOGFILE);
	} else {
		printf("See %s for details of backup run.\n", MONDO_LOGFILE);
	}
	finish(retval);

	return EXIT_SUCCESS;
}
