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

subroutines to handle the archiving of files
*/

/**
 * @file
 * Functions to handle backing up data.
 * This is the main file (at least the longest one) in libmondo.
 */
#include <sys/sem.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>

#include "my-stuff.h"
#include "mondostructures.h"

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

#include "libmondo-string-EXT.h"
#include "libmondo-stream-EXT.h"
#include "libmondo-devices-EXT.h"
#include "libmondo-tools-EXT.h"
#include "newt-specific-EXT.h"
#include "libmondo-fork-EXT.h"
#include "libmondo-files-EXT.h"
#include "libmondo-filelist-EXT.h"
#include "libmondo-tools-EXT.h"
#include "libmondo-verify-EXT.h"
#include "libmondo-archive.h"

#define DVDRWFORMAT 1

#ifndef _SEMUN_H
#define _SEMUN_H

	/**
	 * The semaphore union, provided only in case the user's system doesn't.
	 */
union semun {
	int val;
	struct semid_ds *buf;
	unsigned short int *array;
	struct seminfo *__buf;
};
#endif

extern struct mr_ar_conf *mr_conf;

/*@unused@*/
//static char cvsid[] = "$Id: libmondo-archive.c 1977 2008-06-02 08:49:01Z bruno $";
//
extern char *get_non_rewind_dev(char *);

/* *************************** external global vars ******************/
extern int g_current_media_number;
extern int g_currentY;
extern bool g_text_mode;
extern bool g_exiting;
extern long g_current_progress;
extern FILE *g_tape_stream;
extern long long g_tape_posK;
extern char *g_tmpfs_mountpt;
extern char *g_serial_string;
extern char *g_getfacl;
extern char *g_getfattr;
extern char *MONDO_LOGFILE;

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


/**
 * @addtogroup globalGroup
 * @{
 */
/**
 * The current backup media type in use.
 */
t_bkptype g_backup_media_type = none;
char *g_backup_media_string = NULL;

/**
 * Incremented by each archival thread when it starts up. After that,
 * this is the number of threads running.
 */
int g_current_thread_no = 0;

/* @} - end of globalGroup */

extern int g_noof_rows;

/* Semaphore-related code */

static int set_semvalue(void);
static void del_semvalue(void);
static int semaphore_p(void);
static int semaphore_v(void);

static int g_sem_id;
static int g_sem_key;

/**
 * Initialize the semaphore.
 * @see del_semvalue
 * @see semaphore_p
 * @see semaphore_v
 * @return 1 for success, 0 for failure.
 */
static int set_semvalue(void)	// initializes semaphore
{
	union semun sem_union;
	sem_union.val = 1;
	if (semctl(g_sem_id, 0, SETVAL, sem_union) == -1) {
		return (0);
	}
	return (1);
}

/**
 * Frees (deletes) the semaphore. Failure is indicated by a log
 * message.
 * @see set_semvalue
 */
static void del_semvalue(void)	// deletes semaphore
{
	union semun sem_union;

	if (semctl(g_sem_id, 0, IPC_RMID, sem_union) == -1) {
		mr_msg(3, "Failed to delete semaphore");
	}
}

/**
 * Acquire (increment) the semaphore (change status to P).
 * @return 1 for success, 0 for failure.
 * @see semaphore_v
 */
static int semaphore_p(void)	// changes status to 'P' (waiting)
{
	struct sembuf sem_b;

	sem_b.sem_num = 0;
	sem_b.sem_op = -1;			// P()
	sem_b.sem_flg = SEM_UNDO;
	if (semop(g_sem_id, &sem_b, 1) == -1) {
		mr_msg(3, "semaphore_p failed");
		return (0);
	}
	return (1);
}

/**
 * Free (decrement) the semaphore (change status to V).
 * @return 1 for success, 0 for failure.
 */
static int semaphore_v(void)	// changes status to 'V' (free)
{
	struct sembuf sem_b;

	sem_b.sem_num = 0;
	sem_b.sem_op = 1;			// V()
	sem_b.sem_flg = SEM_UNDO;
	if (semop(g_sem_id, &sem_b, 1) == -1) {
		mr_msg(3, "semaphore_v failed");
		return (0);
	}
	return (1);
}


//------------------------------------------------------


/**
 * Size in megabytes of the buffer afforded to the executable "buffer".
 * This figure is used when we calculate how much data we have probably 'lost'
 * when writing off the end of tape N, so that we can then figure out how much
 * data we must recreate & write to the start of tape N+1.
 */
extern int g_tape_buffer_size_MB;




int
archive_this_fileset_with_star(char *filelist, char *fname, int setno)
{
	int retval = 0;
	unsigned int res = 0;
	int tries = 0;
	char *command = NULL;
	char *tmp = NULL;
	char *p =NULL;
	char *tmp1 = NULL;

	malloc_string(tmp1);

	if (!does_file_exist(filelist)) {
		mr_asprintf(&tmp,
				 "(archive_this_fileset) - filelist %s does not exist",
				 filelist);
		log_to_screen(tmp);
		mr_free(tmp);
		return (1);
	}

	mr_asprintf(&tmp, "echo hi > %s 2> /dev/null", fname);
	if (system(tmp)) {
		fatal_error("Unable to write tarball to scratchdir");
	}
	mr_free(tmp);

	mr_asprintf(&command, "star H=star list=%s -c " STAR_ACL_SZ " file=%s",
			 filelist, fname);

	if (bkpinfo->compression_level > 0) {
		mr_asprintf(&tmp, "%s -bz", command);
		mr_free(command);
		command = tmp;
	}
	mr_asprintf(&tmp, "%s 2>> %s", command, MONDO_LOGFILE);
	mr_free(command);
	command = tmp;
	mr_msg(4, "command = '%s'", command);

	for (res = 99, tries = 0; tries < 3 && res != 0; tries++) {
		mr_msg(5, "command='%s'", command);
		res = system(command);
		strcpy(tmp1, last_line_of_file(MONDO_LOGFILE));
		mr_msg(1, "res=%d; tmp='%s'", res, tmp);
		if (bkpinfo->use_star && (res == 254 || res == 65024)
			&& strstr(tmp, "star: Processed all possible files")
			&& tries > 0) {
			mr_msg(1, "Star returned nonfatal error");
			res = 0;
		}
		if (res) {
			log_OS_error(command);
			p = strstr(command, "-acl ");
			if (p) {
				p[0] = p[1] = p[2] = p[3] = ' ';
				mr_msg(1, "new command = '%s'", command);
			} else {
				mr_msg(3,
						"Attempt #%d failed. Pausing 3 seconds and retrying...",
						tries + 1);
				sleep(3);
			}
		}
	}
	mr_free(command);

	retval += res;
	if (retval) {
		mr_msg(3, "Failed to write set %d", setno);
	} else if (tries > 1) {
		mr_msg(3, "Succeeded in writing set %d, on try #%d", setno,
				tries);
	}

	return (retval);
}


/**
 * Call @c afio to archive the filelist @c filelist to the file @c fname.
 * 
 * @param bkpinfo The backup information structure. Fields used:
 * - @c compression_level
 * - @c scratchdir (only verifies existence)
 * - @c tmpdir (only verifies existence)
 * - @c compression_tool
 * - @c compression_suffix
 * @param filelist The path to a file containing a list of files to be archived
 * in this fileset.
 * @param fname The output file to archive to.
 * @param setno This fileset number.
 * @return The number of errors encountered (0 for success).
 * @ingroup LLarchiveGroup
 */
int
archive_this_fileset(char *filelist, char *fname, int setno)
{

	/*@ int ************************************************************ */
	int retval = 0;
	int res = 0;
	int i = 0;
	int tries = 0;
	static int free_ramdisk_space = 9999;

	/*@ buffers ******************************************************** */
	char *command = NULL;
	char *zipparams = NULL;
	char *tmp = NULL;
	char *tmp1 = NULL;

	assert(bkpinfo != NULL);
	assert_string_is_neither_NULL_nor_zerolength(filelist);
	assert_string_is_neither_NULL_nor_zerolength(fname);

	if (bkpinfo->compression_level > 0 && bkpinfo->use_star) {
		return (archive_this_fileset_with_star(filelist, fname, setno));
	}

	if (!does_file_exist(filelist)) {
		mr_asprintf(&tmp,
				 "(archive_this_fileset) - filelist %s does not exist",
				 filelist);
		log_to_screen(tmp);
		mr_free(tmp);
		return (1);
	}
	mr_asprintf(&tmp, "echo hi > %s 2> /dev/null", fname);
	if (system(tmp)) {
		fatal_error("Unable to write tarball to scratchdir");
	}
	mr_free(tmp);


	if (bkpinfo->compression_level > 0) {
		mr_asprintf(&zipparams, "-Z -P %s -G %d -T 3k", bkpinfo->compression_tool,
				 bkpinfo->compression_level);
		mr_asprintf(&tmp, "%s/do-not-compress-these", MONDO_SHARE);
		if (does_file_exist(tmp)) {
			mr_asprintf(&tmp1, " -E +%s", tmp);
			mr_strcat(zipparams, tmp1);
			mr_free(tmp1);
		} else {
			mr_msg(3, "%s not found. Cannot exclude zipfiles, etc.", tmp);
		}
		mr_free(tmp);
	} else {
		mr_asprintf(&zipparams, " ");
	}

//  make_hole_for_file(fname);

	if (!does_file_exist(bkpinfo->tmpdir)) {
		log_OS_error("tmpdir not found");
		fatal_error("tmpdir not found");
	}
	if (!does_file_exist(bkpinfo->scratchdir)) {
		log_OS_error("scratchdir not found");
		fatal_error("scratchdir not found");
	}
	mr_asprintf(&command, "rm -f %s %s. %s.gz %s.%s", fname, fname, fname,
			 fname, bkpinfo->compression_suffix);
	paranoid_system(command);
	mr_free(command);

	mr_asprintf(&command, "afio -o -b %ld -M 16m %s %s < %s 2>> %s",
			 mr_conf->external_tape_blocksize, zipparams, fname, filelist, MONDO_LOGFILE);
	mr_free(zipparams);

	mr_asprintf(&tmp, "echo hi > %s 2> /dev/null", fname);
	if (system(tmp)) {
		fatal_error("Unable to write tarball to scratchdir");
	}
	mr_free(tmp);

	for (res = 99, tries = 0; tries < 3 && res != 0; tries++) {
		mr_msg(5, "command='%s'", command);
		res = system(command);
		if (res) {
			log_OS_error(command);
			mr_msg(3,
					"Attempt #%d failed. Pausing 3 seconds and retrying...",
					tries + 1);
			sleep(3);
		}
	}
	mr_free(command);

	retval += res;
	if (retval) {
		mr_msg(3, "Failed to write set %d", setno);
	} else if (tries > 1) {
		mr_msg(3, "Succeeded in writing set %d, on try #%d", setno,
				tries);
	}

	if (g_tmpfs_mountpt[0] != '\0') {
		i = atoi(call_program_and_get_last_line_of_output
				 ("df -m -P | grep dev/shm | grep -v none | tr -s ' ' '\t' | cut -f4"));
		if (i > 0) {
			if (free_ramdisk_space > i) {
				free_ramdisk_space = i;
				mr_msg(2, "min(free_ramdisk_space) is now %d",
						free_ramdisk_space);
				if (free_ramdisk_space < 10) {
					fatal_error
						("Please increase PPCFG_RAMDISK_SIZE in my-stuff.h to increase size of ramdisk ");
				}
			}
		}
	}
	return (retval);
}


/**
 * Wrapper function for all the backup commands.
 * Calls these other functions: @c prepare_filelist(),
 * @c call_filelist_chopper(), @c copy_mondo_and_mindi_stuff_to_scratchdir(),
 * @c call_mindi_to_supply_boot_disks(), @c do_that_initial_phase(),
 * @c make_those_afios_phase(), @c make_those_slices_phase(), and
 * @c do_that_final_phase(). If anything fails before @c do_that_initial_phase(),
 * @c fatal_error is called with a suitable message.
 * @param bkpinfo The backup information structure. Uses most fields.
 * @return The number of non-fatal errors encountered (0 for success).
 * @ingroup archiveGroup
 */
int backup_data()
{
	int retval = 0, res = 0;
	char *tmp = NULL;

	assert(bkpinfo != NULL);
	set_g_cdrom_and_g_dvd_to_bkpinfo_value();

	if (bkpinfo->backup_media_type == dvd) {
#ifdef DVDRWFORMAT
		if (!find_home_of_exe("dvd+rw-format")) {
			fatal_error
				("Cannot find dvd+rw-format. Please install it or fix your PATH.");
		}
#endif
		if (!find_home_of_exe("growisofs")) {
			fatal_error
				("Cannot find growisofs. Please install it or fix your PATH.");
		}
	}

	if ((res = prepare_filelist())) {	/* generate scratchdir/filelist.full */
		fatal_error("Failed to generate filelist catalog");
	}
	if (call_filelist_chopper()) {
		fatal_error("Failed to run filelist chopper");
	}

	mr_asprintf(&tmp, "gzip -9 %s/archives/filelist.full",
			 bkpinfo->scratchdir);
	if (run_program_and_log_output(tmp, 2)) {
		fatal_error("Failed to gzip filelist.full");
	}
	mr_free(tmp);
	mr_asprintf(&tmp, "cp -f %s/archives/*list*.gz %s", bkpinfo->scratchdir,
			 bkpinfo->tmpdir);
	if (run_program_and_log_output(tmp, 2)) {
		fatal_error("Failed to copy to tmpdir");
	}
	mr_free(tmp);

	copy_mondo_and_mindi_stuff_to_scratchdir();	// payload, too, if it exists
#if __FreeBSD__ == 5
	mr_allocstr(bkpinfo->kernel_path, "/boot/kernel/kernel");
#elif __FreeBSD__ == 4
	mr_allocstr(bkpinfo->kernel_path, "/kernel");
#elif linux
	if (figure_out_kernel_path_interactively_if_necessary
		(bkpinfo->kernel_path)) {
		fatal_error
			("Kernel not found. Please specify manually with the '-k' switch.");
	}
#else
#error "I don't know about this system!"
#endif
	if ((res = call_mindi_to_supply_boot_disks())) {
		fatal_error("Failed to generate boot+data disks");
	}
	retval += do_that_initial_phase();	// prepare
	mr_asprintf(&tmp, "rm -f %s/images/*.iso", bkpinfo->scratchdir);
	run_program_and_log_output(tmp, 1);
	mr_free(tmp);
	retval += make_those_afios_phase();	// backup regular files
	retval += make_those_slices_phase();	// backup BIG files
	retval += do_that_final_phase();	// clean up
	mr_msg(1, "Creation of archives... complete.");
	if (bkpinfo->verify_data) {
		sleep(2);
	}
	return (retval);
}


/**
 * Call Mindi to generate boot and data disks.
 * @note This binds correctly to the new Perl version of mindi.
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_media_type
 * - @c boot_loader
 * - @c boot_device
 * - @c compression_level
 * - @c differential
 * - @c exclude_paths
 * - @c image_devs
 * - @c kernel_path
 * - @c make_cd_use_lilo
 * - @c media_device
 * - @c media_size
 * - @c nonbootable_backup
 * - @c tmpdir
 *
 * @return The number of errors encountered (0 for success)
 * @bug The code to automagically determine the boot drive
 * is messy and system-dependent. In particular, it breaks
 * for Linux RAID and LVM users.
 * @ingroup MLarchiveGroup
 */
int call_mindi_to_supply_boot_disks()
{
	/*@ buffer ************************************************************ */
	char *tmp = NULL;
	char *tmp1 = NULL;
	char *tmp2 = NULL;
	char *command = NULL;
	char *bootldr_str = NULL;
	char *tape_device = NULL;
	char *last_filelist_number = NULL;
	char *broken_bios_sz = NULL;
	char *cd_recovery_sz = NULL;
	char *tape_size_sz = NULL;
	char *devs_to_exclude = NULL;
	char *use_lilo_sz = NULL;
	char *bootdev = NULL;
	char *ntapedev = NULL;

	/*@ char ************************************************************** */
	char ch = '\0';

	/*@ long     ********************************************************** */
	long lines_in_filelist = 0;

	/*@ int         ************************************************************* */
	int res = 0;
	long estimated_total_noof_slices = 0;

	FILE *fd = NULL;
	FILE *fd1 = NULL;

	assert(bkpinfo != NULL);
	malloc_string(last_filelist_number);
	malloc_string(devs_to_exclude);
	malloc_string(bootdev);

	mr_asprintf(&tmp,
			"echo '%s' | tr -s ' ' '\n' | grep -E '^/dev/.*$' | tr -s '\n' ' ' | awk '{print $0\"\\n\";}'",
			bkpinfo->exclude_paths);

	strcpy(devs_to_exclude, call_program_and_get_last_line_of_output(tmp));
	mr_free(tmp);

	mr_asprintf(&tmp, "devs_to_exclude = '%s'", devs_to_exclude);
	mr_msg(2, tmp);
	mr_free(tmp);
	mvaddstr_and_log_it(g_currentY, 0,
						"Calling MINDI to create boot+data disks");
	mr_asprintf(&tmp, "%s/filelist.full", bkpinfo->tmpdir);
	if (!does_file_exist(tmp)) {
		mr_free(tmp);
		mr_asprintf(&tmp, "%s/tmpfs/filelist.full", bkpinfo->tmpdir);
		if (!does_file_exist(tmp)) {
			fatal_error
				("Cannot find filelist.full, so I cannot count its lines");
		}
	}
	lines_in_filelist = count_lines_in_file(tmp);
	strcpy(last_filelist_number, last_line_of_file(tmp));
	mr_free(tmp);

	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		mr_asprintf(&tape_size_sz, "%ld", bkpinfo->media_size);
		ntapedev = get_non_rewind_dev(bkpinfo->media_device);
		if ((bkpinfo->use_obdr) && (ntapedev != NULL)) {
			mr_free(bkpinfo->media_device);
			bkpinfo->media_device = ntapedev;
		} else {
			if (ntapedev == NULL) {
				log_it("Not able to create OBDR - Restore will have to be done manually");
			}
		}
		mr_asprintf(&tape_device, bkpinfo->media_device);
	} else {
		mr_asprintf(&tape_size_sz, " ");
		mr_asprintf(&tape_device, " ");
	}
	/* BERLIOS: This parameter is not used after? */
	mr_free(tape_size_sz);

	mr_asprintf(&broken_bios_sz, "yes");	/* assume so */
	if (g_cd_recovery) {
		mr_asprintf(&cd_recovery_sz, "yes");
	} else {
		mr_asprintf(&cd_recovery_sz, "no");
	}

	if (!bkpinfo->nonbootable_backup
		&& (bkpinfo->boot_loader == '\0'
			|| bkpinfo->boot_device[0] == '\0')) {

#ifdef __FreeBSD__
		strcpy(bootdev, call_program_and_get_last_line_of_output
			   ("mount | grep ' /boot ' | head -1 | cut -d' ' -f1 | sed 's/\\([0-9]\\).*/\\1/'"));
		if (!bootdev[0]) {
			strcpy(bootdev, call_program_and_get_last_line_of_output
				   ("mount | grep ' / ' | head -1 | cut -d' ' -f1 | sed 's/\\([0-9]\\).*/\\1/'"));
		}
#else
#ifdef __IA64__
		strcpy(bootdev, call_program_and_get_last_line_of_output
			   ("mount | grep ' /boot/efi ' | head -1 | cut -d' ' -f1 | sed 's/[0-9].*//'"));
#else
		strcpy(bootdev, call_program_and_get_last_line_of_output
			   ("mount | grep ' /boot ' | head -1 | cut -d' ' -f1 | sed 's/[0-9].*//'"));
#endif
		if (strstr(bootdev, "/dev/cciss/")) {
#ifdef __IA64__
			strcpy(bootdev, call_program_and_get_last_line_of_output
				   ("mount | grep ' /boot/efi ' | head -1 | cut -d' ' -f1 | cut -dp -f1"));
#else
			strcpy(bootdev, call_program_and_get_last_line_of_output
				   ("mount | grep ' /boot ' | head -1 | cut -d' ' -f1 | cut -dp -f1"));
#endif
		}
		if (!bootdev[0]) {
			strcpy(bootdev, call_program_and_get_last_line_of_output
				   ("mount | grep ' / ' | head -1 | cut -d' ' -f1 | sed 's/[0-9].*//'"));
			if (strstr(bootdev, "/dev/cciss/")) {
				strcpy(bootdev, call_program_and_get_last_line_of_output
					   ("mount | grep ' / ' | head -1 | cut -d' ' -f1 | cut -dp -f1"));
			}
		}
#endif
		if (bootdev[0])
			ch = which_boot_loader(bootdev);
		else
			ch = 'U';

		if (bkpinfo->boot_loader != '\0') {
			mr_asprintf(&tmp, "User specified boot loader. It is '%c'.",
					bkpinfo->boot_loader);
			mr_msg(2, tmp);
			mr_free(tmp);
		} else {
			bkpinfo->boot_loader = ch;
		}
		if (bkpinfo->boot_device[0] != '\0') {
			mr_asprintf(&tmp, "User specified boot device. It is '%s'.",
					bkpinfo->boot_device);
			mr_msg(2, tmp);
			mr_free(tmp);
		} else {
			strcpy(bkpinfo->boot_device, bootdev);
		}
	}

	if (
#ifdef __FreeBSD__
		   bkpinfo->boot_loader != 'B' && bkpinfo->boot_loader != 'D' &&
#endif
#ifdef __IA64__
		   bkpinfo->boot_loader != 'E' &&
#endif
		   bkpinfo->boot_loader != 'L' && bkpinfo->boot_loader != 'G'
		   && bkpinfo->boot_loader != 'R' && !bkpinfo->nonbootable_backup)
	{
		fatal_error
			("Please specify your boot loader and device, e.g. -l GRUB -f /dev/hda.\nType 'man mondoarchive' to read the manual.");
	}
	if (bkpinfo->boot_loader == 'L') {
		mr_asprintf(&bootldr_str, "LILO");
		if (!does_file_exist("/etc/lilo.conf")) {
			fatal_error
				("The de facto standard location for your boot loader's config file is /etc/lilo.conf.\nBut I cannot find it there. What is wrong with your Linux distribution?");
		}
	} else if (bkpinfo->boot_loader == 'G') {
		mr_asprintf(&bootldr_str, "GRUB");
		if (!does_file_exist("/etc/grub.conf")
			&& does_file_exist("/boot/grub/grub.conf")) {
			run_program_and_log_output
				("ln -sf /boot/grub/grub.conf /etc/grub.conf", 5);
		}
		/* Detect Debian's grub config file */
		else if (!does_file_exist("/etc/grub.conf")
				 && does_file_exist("/boot/grub/menu.lst")) {
			run_program_and_log_output
				("ln -s /boot/grub/menu.lst /etc/grub.conf", 5);
		}
		if (!does_file_exist("/etc/grub.conf")) {
			fatal_error
				("The de facto standard location for your boot loader's config file is /etc/grub.conf.\nBut I cannot find it there. What is wrong with your Linux distribution?\nTry 'ln -s /boot/grub/menu.lst /etc/grub.conf'...");
		}
	} else if (bkpinfo->boot_loader == 'E') {
		mr_asprintf(&bootldr_str, "ELILO");
		/* BERLIOS: fix it for Debian, Mandrake, ... */
		if (!does_file_exist("/etc/elilo.conf")
			&& does_file_exist("/boot/efi/efi/redhat/elilo.conf")) {
			run_program_and_log_output
				("ln -sf /boot/efi/efi/redhat/elilo.conf /etc/elilo.conf",
				 5);
		}
		if (!does_file_exist("/etc/elilo.conf")
			&& does_file_exist("/boot/efi/efi/SuSE/elilo.conf")) {
			run_program_and_log_output
				("ln -sf /boot/efi/efi/SuSE/elilo.conf /etc/elilo.conf",
				 5);
		}
		if (!does_file_exist("/etc/elilo.conf")
			&& does_file_exist("/boot/efi/efi/debian/elilo.conf")) {
			run_program_and_log_output
				("ln -sf /boot/efi/efi/debian/elilo.conf /etc/elilo.conf",
				 5);
		}
		if (!does_file_exist("/etc/elilo.conf")
			&& does_file_exist("/boot/efi/debian/elilo.conf")) {
			run_program_and_log_output
				("ln -sf /boot/efi/debian/elilo.conf /etc/elilo.conf",
				 5);
		}
		if (!does_file_exist("/etc/elilo.conf")) {
			fatal_error
				("The de facto mondo standard location for your boot loader's config file is /etc/elilo.conf\nBut I cannot find it there. What is wrong with your Linux distribution?\nTry finding it under /boot/efi and do 'ln -s /boot/efi/..../elilo.conf /etc/elilo.conf'");
		}
	} else if (bkpinfo->boot_loader == 'R') {
		mr_asprintf(&bootldr_str, "RAW");
	}
#ifdef __FreeBSD__
	else if (bkpinfo->boot_loader == 'D') {
		mr_asprintf(&bootldr_str, "DD");
	}

	else if (bkpinfo->boot_loader == 'B') {
		mr_asprintf(&bootldr_str, "BOOT0");
	}
#endif
	else {
		mr_asprintf(&bootldr_str, "unknown");
	}
	mr_asprintf(&tmp, "Your boot loader is %s and it boots from %s",
			bootldr_str, bkpinfo->boot_device);
	log_to_screen(tmp);
	mr_free(tmp);
	mr_asprintf(&tmp, "%s/BOOTLOADER.DEVICE", bkpinfo->tmpdir);
	if (write_one_liner_data_file(tmp, bkpinfo->boot_device)) {
		mr_msg(1, "Unable to write one-liner boot device");
	}

	estimated_total_noof_slices =
		size_of_all_biggiefiles_K(bkpinfo) / bkpinfo->optimal_set_size + 1;
	mr_asprintf(&command, "mkdir -p %s/images", bkpinfo->scratchdir);
	if (system(command)) {
		res++;
		log_OS_error("Unable to make images directory");
	}
	mr_free(command);

	/* Prepare interface with mindi through a configuration file
	 * under /var/cache/mondo by default 
	 * and the mondorestore configuration file at the same time that
	 * will be included by mindi on the initrd */

	fd = mr_fopen(MONDO_CACHE"/mindi.conf", "w");
	fd1 = mr_fopen(MONDORESTORECFG, "a");

	mr_fprintf(fd, "mindi_use_own_kernel=yes\n");
	if (strcmp(mr_conf->mondo_kernel,"FAILSAFE") == 0) {
	} else {
	}
	mr_fprintf(fd, "mindi_kernel=%s\n", bkpinfo->kernel_path);
	mr_fprintf(fd, "mindi_additional_mods=%s\n", mr_conf->additional_modules);

	mr_fprintf(fd1, "files-in-filelist=%ld\n", lines_in_filelist);
	mr_fprintf(fd1, "internal-tape-block-size=%ld\n", bkpinfo->internal_tape_block_size);
	mr_fprintf(fd1, "total-slices=%ld\n", estimated_total_noof_slices);
	mr_fprintf(fd1, "excluded-devs=%s\n", devs_to_exclude);
	mr_fprintf(fd1, "image-devs=%s\n", bkpinfo->image_devs);
	mr_fprintf(fd1, "last-filelist-number=%s\n", last_filelist_number);
	mr_fprintf(fd1, "bootloader.name=%s\n", bootldr_str);
	mr_fprintf(fd1, "bootloader.device=%s\n", bkpinfo->boot_device);

	mr_free(bootldr_str);

	switch (bkpinfo->backup_media_type) {
	case cdr:
		mr_fprintf(fd1, "backup-media-type=cdr\n");
		break;
	case cdrw:
		mr_fprintf(fd1, "backup-media-type=cdrw\n");
		break;
	case cdstream:
		mr_fprintf(fd1, "backup-media-type=cdstream\n");
		break;
	case tape:
		mr_fprintf(fd1, "backup-media-type=tape\n");
		break;
	case udev:
		mr_fprintf(fd1, "backup-media-type=udev\n");
		break;
	case iso:
		mr_fprintf(fd1, "backup-media-type=iso\n");
		break;
	case nfs:
		mr_fprintf(fd1, "backup-media-type=nfs\n");
		break;
	case dvd:
		mr_fprintf(fd1, "backup-media-type=dvd\n");
		break;
	case usb:
		mr_fprintf(fd1, "backup-media-type=usb\n");
		break;
	default:
		fatal_error("Unknown backup_media_type");
	}

	if (bkpinfo->backup_media_type == usb) {
		mr_fprintf(fd, "mindi_write_usb=yes\n");
		mr_fprintf(fd, "mindi_usb_device=%s\n", bkpinfo->media_device);
	}
	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		mr_fprintf(fd, "mindi_write_tape=yes\n");
		mr_fprintf(fd, "mindi_tape_device=%s\n", bkpinfo->media_device);
		mr_fprintf(fd1, "media-dev=%s\n", bkpinfo->media_device);
		mr_fprintf(fd1, "media-size=%ld\n", bkpinfo->media_size);
	}
	if (bkpinfo->compression_level > 0) {
		mr_fprintf(fd1, "use-comp=yes\n");
	} else {
		mr_fprintf(fd1, "use-comp=no\n");
	}
	if (bkpinfo->compression_tool) {
		mr_fprintf(fd1, "compression_tool=%s\n",bkpinfo->compression_tool);
	}
	if (bkpinfo->compression_suffix) {
		mr_fprintf(fd1, "compression_suffix=%s\n",bkpinfo->compression_suffix);
	}
	if (bkpinfo->compression_type != none) {
		mr_fprintf(fd1, "compression_type=%d\n",bkpinfo->compression_type);
	}
	if (bkpinfo->use_star) {
		mr_fprintf(fd1, "use-star=yes\n");
	} else {
		mr_fprintf(fd1, "use-star=no\n");
	}
	if (g_getfattr) {
		mr_fprintf(fd1, "xattr=yes\n");
	} else {
		mr_fprintf(fd1, "xattr=no\n");
	}
	if (g_getfacl) {
		mr_fprintf(fd1, "acl=yes\n");
	} else {
		mr_fprintf(fd1, "acl=no\n");
	}
	if (bkpinfo->use_obdr) {
		asprintf(&tmp1, "%s/OBDR", bkpinfo->tmpdir);
		if (write_one_liner_data_file(tmp1, "TRUE")) {
			log_msg(1, "%ld: Unable to write one-liner OBDR",
				__LINE__);
		}
		paranoid_free(tmp1);
	}

	if (g_cd_recovery) {
		mr_fprintf(fd1, "use-cdrecovery=yes\n");
	} else {
		mr_fprintf(fd1, "use-cdrecovery=no\n");
	}

	if (bkpinfo->make_cd_use_lilo) {
		mr_fprintf(fd1, "use-lilo=yes\n");
	} else {
		mr_fprintf(fd1, "use-lilo=no\n");
	}
	if (bkpinfo->nonbootable_backup) {
		mr_fprintf(fd1, "non-bootable=yes\n");
	} else {
		mr_fprintf(fd1, "non-bootable=no\n");
	}
	if (bkpinfo->differential) {
		mr_fprintf(fd1, "differential=yes\n");
	} else {
		mr_fprintf(fd1, "differential=no\n");
	}
	if (mr_conf->mondo_create_mindi_cd) {
		mr_fprintf(fd1, "mindi_write_cd=yes\n");
	} else {
		mr_fprintf(fd1, "mindi_write_cd=no\n");
	}

	mr_fclose(fd);
	mr_fprintf(fd1, "datestamp=%s\n", mr_date());
	mr_fclose(fd1);

	mr_asprintf(&command, "mindi --custom '%s' '%s/images'", 
				bkpinfo->tmpdir, bkpinfo->scratchdir);
			//bkpinfo->tmpdir,		// parameter #2
			//bkpinfo->scratchdir,	// parameter #3
			//bkpinfo->kernel_path,	// parameter #4
			//tape_device,			// parameter #5
			//tape_size_sz,			// parameter #6
			//lines_in_filelist,		// parameter #7 (INT)
			//use_lzo_sz,				// parameter #8
			//cd_recovery_sz,			// parameter #9
			//bkpinfo->image_devs,	// parameter #10
			//broken_bios_sz,			// parameter #11 always yes
			//last_filelist_number,	// parameter #12 (STRING)
			//estimated_total_noof_slices,	// parameter #13 (INT)
			//devs_to_exclude,		// parameter #14
			//use_comp_sz,			// parameter #15
			//use_lilo_sz,			// parameter #16
			//use_star_sz,			// parameter #17
			//bkpinfo->internal_tape_block_size,	// parameter #18 (LONG)
			//bkpinfo->differential,	// parameter #19 (INT)
			//use_gzip_sz);			// parameter #20 (STRING)

	mr_msg(2, command);

	res = run_program_and_log_to_screen(command, "Generating boot+data disks");
	mr_free(command);
	if (bkpinfo->nonbootable_backup) {
		res = 0;
	}							// hack
	if (!res) {
		log_to_screen("Boot+data disks were created OK");
		mr_asprintf(&command, "mkdir -p "MINDI_CACHE);
		mr_msg(2, command);
		run_program_and_log_output(command, FALSE);
		mr_free(command);

		mr_asprintf(&command,
				"cp -f %s/images/mindi.iso %s/mondorescue.iso",
				bkpinfo->scratchdir, MINDI_CACHE);
		mr_msg(2, command);
		run_program_and_log_output(command, FALSE);
		mr_free(command);

		if (bkpinfo->nonbootable_backup) {
			mr_asprintf(&command, "cp -f %s/all.tar.gz %s/images",
					bkpinfo->tmpdir, bkpinfo->scratchdir);
			if (system(command)) {
				fatal_error("Unable to create temporary all tarball");
			}
			mr_free(command);
			
		}
/* BERLIOS: Not executed ?
		sprintf(command, "cp -f %s/mindi-*oot*.img %s/images",
*/
		/* For USB we already have everything on the key */
		if (bkpinfo->backup_media_type == usb) {
			mr_asprintf(&command, "rm -rf %s/images", bkpinfo->scratchdir);
			run_program_and_log_output(command, FALSE);
			mr_free(command);
		} else {
			mr_asprintf(&tmp, "cp -f %s/images/all.tar.gz %s",
				 bkpinfo->scratchdir, bkpinfo->tmpdir);
			if (system(tmp)) {
				fatal_error("Cannot find all.tar.gz in tmpdir");
			mr_free(tmp);
			}
		}

		if (res) {
			mvaddstr_and_log_it(g_currentY++, 74, "Errors.");
		} else {
			mvaddstr_and_log_it(g_currentY++, 74, "Done.");
		}
	} else {
		log_to_screen("Mindi failed to create your boot+data disks.");
		mr_asprintf(&command, "grep 'Fatal error' /var/log/mindi.log");
		malloc_string(tmp);
		strcpy(tmp,call_program_and_get_last_line_of_output(command));
		mr_free(command);
		if (strlen(tmp) > 1) {
			popup_and_OK(tmp);
		}
		mr_free(tmp);
	}
	mr_free(last_filelist_number);
	mr_free(devs_to_exclude);
	mr_free(bootdev);
	return (res);
}


/**
 * Maximum number of filesets allowed in this function.
 */
#define MAX_NOOF_SETS_HERE 32767

/**
 * Offset of the bkpinfo pointer (in bytes) from the
 * buffer passed to create_afio_files_in_background.
 */
#define BKPINFO_LOC_OFFSET (16+MAX_NOOF_SETS_HERE/8+16)

/**
 * Main function for each @c afio thread.
 * @param inbuf A transfer block containing:
 * - @c p_last_set_archived: [offset 0] pointer to an @c int
 *   containing the last set archived.
 * - @c p_archival_threads_running: [offset 4] pointer to an @c int
 *   containing the number of archival threads currently running.
 * - @c p_next_set_to_archive: [offset 8] pointer to an @c int containing
 *   the next set that should be archived.
 * - @c p_list_of_fileset_flags: [offset 12] @c char pointer pointing to a
 *   bit array, where each bit corresponds to a filelist (1=needs
 *   to be archived, 0=archived).
 * - @c bkpinfo: [offset BKPINFO_LOC_OFFSET] pointer to backup information
 *   structure. Fields used:
 *   - @c tmpdir
 *   - @c compression_suffix
 *
 * Any of the above may be modified by the caller at any time.
 *
 * @bug Assumes @c int pointers are 4 bytes.
 * @see archive_this_fileset
 * @see make_afioballs_and_images
 * @return NULL, always.
 * @ingroup LLarchiveGroup
 */
void *create_afio_files_in_background(void *inbuf)
{
	long int archiving_set_no;
	char *archiving_filelist_fname;
	char *archiving_afioball_fname;
	char *curr_xattr_list_fname = NULL;
	char *curr_acl_list_fname;

	struct s_bkpinfo *bkpinfo_bis;
	char *tmp = NULL;
	int res = 0, retval = 0;
	int *p_archival_threads_running;
	int *p_last_set_archived;
	int *p_next_set_to_archive;
	char *p_list_of_fileset_flags;
	int this_thread_no = g_current_thread_no++;

	malloc_string(archiving_filelist_fname);
	malloc_string(archiving_afioball_fname);
	p_last_set_archived = (int *) inbuf;
	p_archival_threads_running = (int *) (inbuf + 4);
	p_next_set_to_archive = (int *) (inbuf + 8);
	p_list_of_fileset_flags = (char *) (inbuf + 12);
	bkpinfo_bis = (struct s_bkpinfo *) (inbuf + BKPINFO_LOC_OFFSET);

	sprintf(archiving_filelist_fname, FILELIST_FNAME_RAW_SZ,
			bkpinfo->tmpdir, 0L);
	for (archiving_set_no = 0; does_file_exist(archiving_filelist_fname);
		 sprintf(archiving_filelist_fname, FILELIST_FNAME_RAW_SZ,
				 bkpinfo->tmpdir, archiving_set_no)) {
		if (g_exiting) {
			fatal_error("Execution run aborted (pthread)");
		}
		if (archiving_set_no >= MAX_NOOF_SETS_HERE) {
			fatal_error
				("Maximum number of filesets exceeded. Adjust MAX_NOOF_SETS_HERE, please.");
		}
		if (!semaphore_p()) {
			mr_msg(3, "P sem failed (pid=%d)", (int) getpid());
			fatal_error("Cannot get semaphore P");
		}
		if (archiving_set_no < *p_next_set_to_archive) {
			archiving_set_no = *p_next_set_to_archive;
		}
		*p_next_set_to_archive = *p_next_set_to_archive + 1;
		if (!semaphore_v()) {
			fatal_error("Cannot get semaphore V");
		}

		/* backup this set of files */
		sprintf(archiving_afioball_fname, AFIOBALL_FNAME_RAW_SZ,
				bkpinfo->tmpdir, archiving_set_no, bkpinfo->compression_suffix);
		sprintf(archiving_filelist_fname, FILELIST_FNAME_RAW_SZ,
				bkpinfo->tmpdir, archiving_set_no);
		if (!does_file_exist(archiving_filelist_fname)) {
			mr_msg(3,
					"[%d:%d] - well, I would archive %d, except that it doesn't exist. I'll stop now.",
					getpid(), this_thread_no,
					archiving_set_no);
			break;
		}

		mr_asprintf(&tmp, AFIOBALL_FNAME_RAW_SZ, bkpinfo->tmpdir,
				 archiving_set_no - ARCH_BUFFER_NUM, bkpinfo->compression_suffix);
		if (does_file_exist(tmp)) {
			mr_msg(4, "[%d:%d] - waiting for storer",
					 getpid(), this_thread_no);
			while (does_file_exist(tmp)) {
				sleep(1);
			}
			mr_msg(4, "[%d] - continuing", getpid());
		}
		mr_free(tmp);

		mr_msg(4, "[%d:%d] - EXATing %d...", getpid(),
				this_thread_no, archiving_set_no);
		if (g_getfattr) {
			mr_asprintf(&curr_xattr_list_fname, XATTR_LIST_FNAME_RAW_SZ,
				bkpinfo->tmpdir, archiving_set_no);
			get_fattr_list(archiving_filelist_fname, curr_xattr_list_fname);
			mr_free(curr_xattr_list_fname);
		}
		if (g_getfacl) {
			mr_asprintf(&curr_acl_list_fname, ACL_LIST_FNAME_RAW_SZ,
				bkpinfo->tmpdir, archiving_set_no);
			get_acl_list(archiving_filelist_fname, curr_acl_list_fname);
			mr_free(curr_acl_list_fname);
		}

		mr_msg(4, "[%d:%d] - archiving %d...", getpid(),
				this_thread_no, archiving_set_no);
		res =
			archive_this_fileset(archiving_filelist_fname,
								 archiving_afioball_fname,
								 archiving_set_no);
		retval += res;

		if (res) {
			mr_asprintf(&tmp,
					 "Errors occurred while archiving set %ld. Please review logs.",
					 archiving_set_no);
			log_to_screen(tmp);
			mr_free(tmp);
		}
		if (!semaphore_p()) {
			fatal_error("Cannot get semaphore P");
		}

		set_bit_N_of_array(p_list_of_fileset_flags, archiving_set_no, 5);

		if (*p_last_set_archived < archiving_set_no) {
			*p_last_set_archived = archiving_set_no;
		}						// finished archiving this one

		if (!semaphore_v()) {
			fatal_error("Cannot get semaphore V");
		}
		mr_msg(4, "[%d:%d] - archived %d OK", getpid(),
				this_thread_no, archiving_set_no);
		archiving_set_no++;
	}
	if (!semaphore_p()) {
		fatal_error("Cannot get semaphore P");
	}
	(*p_archival_threads_running)--;
	if (!semaphore_v()) {
		fatal_error("Cannot get semaphore V");
	}
	mr_msg(3, "[%d:%d] - exiting", getpid(),
			this_thread_no);
	mr_free(archiving_filelist_fname);
	mr_free(archiving_afioball_fname);
	pthread_exit(NULL);
}


/**
 * Finalize the backup.
 * For streaming backups, this writes the closing block
 * to the stream. For CD-based backups, this creates
 * the final ISO image.
 * @param bkpinfo The backup information structure, used only
 * for the @c backup_media_type.
 * @ingroup MLarchiveGroup
 */
int do_that_final_phase()
{

	/*@ int ************************************** */
	int res = 0;
	int retval = 0;

	/*@ buffers ********************************** */

	assert(bkpinfo != NULL);
	mvaddstr_and_log_it(g_currentY, 0,
						"Writing any remaining data to media         ");

	mr_msg(1, "Closing tape/CD/USB ... ");
	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		/* write tape/cdstream */
		closeout_tape();
	} else {
		/* write final ISO/USB */
		res = write_final_iso_if_necessary();
		retval += res;
		if (res) {
			mr_msg(1, "write_final_iso_if_necessary returned an error");
		}
	}
	mr_msg(2, "Fork is exiting ... ");

	mvaddstr_and_log_it(g_currentY++, 74, "Done.");

	/* final stuff */
	if (retval) {
		mvaddstr_and_log_it(g_currentY++, 74, "Errors.");
	} else {
		mvaddstr_and_log_it(g_currentY++, 74, "Done.");
	}

	return (retval);
}


/**
 * Initialize the backup.
 * Does the following:
 * - Sets up the serial number.
 * - For streaming backups, opens the tape stream and writes the data disks
 *   and backup headers.
 * - For CD-based backups, wipes the ISOs in the target directory.
 *
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_media_type
 * - @c writer_speed
 * - @c prefix
 * - @c isodir
 * - @c media_device
 * - @c scratchdir
 * - @c tmpdir
 * @return The number of errors encountered (0 for success).
 * @ingroup MLarchiveGroup
 */
int do_that_initial_phase()
{
	/*@ int *************************************** */
	int retval = 0;

	/*@ buffers *********************************** */
	char *command, *tmp_file, *data_disks_file;

	assert(bkpinfo != NULL);
	malloc_string(command);

	mr_asprintf(&data_disks_file, "%s/all.tar.gz", bkpinfo->tmpdir);

	snprintf(g_serial_string, MAX_STR_LEN - 1,
			 call_program_and_get_last_line_of_output("dd \
if=/dev/urandom bs=16 count=1 2> /dev/null | \
hexdump | tr -s ' ' '0' | head -n1"));
	mr_strip_spaces(g_serial_string);
	strcat(g_serial_string, "...word.");
	mr_msg(2, "g_serial_string = '%s'", g_serial_string);
	assert(strlen(g_serial_string) < MAX_STR_LEN);

	mr_asprintf(&tmp_file, "%s/archives/SERIAL-STRING", bkpinfo->scratchdir);
	if (write_one_liner_data_file(tmp_file, g_serial_string)) {
		mr_msg(1, "%ld: Failed to write serial string", __LINE__);
	}
	mr_free(tmp_file);

	mvaddstr_and_log_it(g_currentY, 0, "Preparing to archive your data");
	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		if (bkpinfo->backup_media_type == cdstream) {
			openout_cdstream(bkpinfo->media_device, bkpinfo->writer_speed);
		} else {
			openout_tape();	/* sets g_tape_stream */
		}
		if (!g_tape_stream) {
			fatal_error("Cannot open backup (streaming) device");
		}
		mr_msg(1, "Backup (stream) opened OK");
		write_data_disks_to_stream(data_disks_file);
	} else {
		if (bkpinfo->backup_media_type == usb) {
			mr_msg(1, "Backing up to USB's");
		} else {
			mr_msg(1, "Backing up to CD's");
		}
	}
	mr_free(data_disks_file);

	mr_asprintf(&command, "rm -f %s/%s/%s-[1-9]*.iso", bkpinfo->isodir,
			 bkpinfo->nfs_remote_dir, bkpinfo->prefix);
	paranoid_system(command);
	mr_free(command);

	wipe_archives(bkpinfo->scratchdir);
	mvaddstr_and_log_it(g_currentY++, 74, "Done.");
	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		write_header_block_to_stream((off_t)0, "start-of-tape",
									 BLK_START_OF_TAPE);
		write_header_block_to_stream((off_t)0, "start-of-backup",
									 BLK_START_OF_BACKUP);
	}
	return (retval);
}


/**
 * Get the <tt>N</tt>th bit of @c array.
 * @param array The bit-array (as a @c char pointer).
 * @param N The number of the bit you want.
 * @return TRUE (bit is set) or FALSE (bit is not set).
 * @see set_bit_N_of_array
 * @ingroup utilityGroup
 */
bool get_bit_N_of_array(char *array, int N)
{
	int element_number;
	int bit_number;
	int mask;

	element_number = N / 8;
	bit_number = N % 8;
	mask = 1 << bit_number;
	if (array[element_number] & mask) {
		return (TRUE);
	} else {
		return (FALSE);
	}
}


/**
 * @addtogroup LLarchiveGroup
 * @{
 */
/**
 * Start up threads to archive your files.
 *
 * This function starts @c ARCH_THREADS threads,
 * each starting execution in @c create_afio_files_in_background().
 * Each thread will archive individual filesets, based on the
 * pointers passed to it and continually updated, until all files
 * have been backed up. This function coordinates the threads
 * and copies their output to the @c scratchdir.
 *
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_media_type
 * - @c scratchdir
 * - @c tmpdir
 * - @c compression_suffix
 *
 * @return The number of errors encountered (0 for success)
 */
int make_afioballs_and_images()
{

	/*@ int ************************************************** */
	int retval = 0;
	long int storing_set_no = 0;
	int res = 0;
	bool done_storing = FALSE;
	char *result_str;
	char *transfer_block;
	void *vp;
	void **pvp;

	/*@ buffers ********************************************** */
	char *storing_filelist_fname;
	char *storing_afioball_fname;
	char *tmp = NULL;
	char *media_usage_comment;
	pthread_t archival_thread[ARCH_THREADS];
	char *p_list_of_fileset_flags;
	int *p_archival_threads_running;
	int *p_last_set_archived;
	int *p_next_set_to_archive;
	int noof_threads;
	int i;
	char *curr_xattr_list_fname = NULL;
	char *curr_acl_list_fname = NULL;
	int misc_counter_that_is_not_important = 0;

	mr_msg(8, "here");
	assert(bkpinfo != NULL);
	/* BERLIOS: To be removed */
	malloc_string(result_str);
	malloc_string(curr_xattr_list_fname);
	malloc_string(curr_acl_list_fname);
	malloc_string(storing_filelist_fname);
	malloc_string(media_usage_comment);
	malloc_string(storing_afioball_fname);
	transfer_block =
		mr_malloc(sizeof(struct s_bkpinfo) + BKPINFO_LOC_OFFSET + 64);
	memset((void *) transfer_block, 0,
		   sizeof(struct s_bkpinfo) + BKPINFO_LOC_OFFSET + 64);
	p_last_set_archived = (int *) transfer_block;
	p_archival_threads_running = (int *) (transfer_block + 4);
	p_next_set_to_archive = (int *) (transfer_block + 8);
	p_list_of_fileset_flags = (char *) (transfer_block + 12);
	memcpy((void *) (transfer_block + BKPINFO_LOC_OFFSET),
		   (void *) bkpinfo, sizeof(struct s_bkpinfo));
	pvp = &vp;
	vp = (void *) result_str;
	*p_archival_threads_running = 0;
	*p_last_set_archived = -1;
	*p_next_set_to_archive = 0;
	log_to_screen("Archiving regular files");
	open_progress_form(_("Backing up filesystem"),
					   _("I am backing up your live filesystem now."),
					   _("Please wait. This may take a couple of hours."),
					   _("Working..."),
					   get_last_filelist_number() + 1);

	srand((unsigned int) getpid());
	g_sem_key = 1234 + random() % 30000;
	if ((g_sem_id =
		 semget((key_t) g_sem_key, 1,
				IPC_CREAT | S_IREAD | S_IWRITE)) == -1) {
		fatal_error("MABAI - unable to semget");
	}
	if (!set_semvalue()) {
		fatal_error("Unable to init semaphore");
	}							// initialize semaphore
	for (noof_threads = 0; noof_threads < ARCH_THREADS; noof_threads++) {
		mr_msg(8, "Creating thread #%d", noof_threads);
		(*p_archival_threads_running)++;
		if ((res =
			 pthread_create(&archival_thread[noof_threads], NULL,
							create_afio_files_in_background,
							(void *) transfer_block))) {
			fatal_error("Unable to create an archival thread");
		}
	}

	mr_msg(8, "About to enter while() loop");
	while (!done_storing) {
		if (g_exiting) {
			fatal_error("Execution run aborted (main loop)");
		}
		if (*p_archival_threads_running == 0
			&& *p_last_set_archived == storing_set_no - 1) {
			mr_msg(2,
					"No archival threads are running. The last stored set was %d and I'm looking for %d. Take off your make-up; the party's over... :-)",
					*p_last_set_archived, storing_set_no);
			done_storing = TRUE;
		} else
			if (!get_bit_N_of_array
				(p_list_of_fileset_flags, storing_set_no)) {
			misc_counter_that_is_not_important =
				(misc_counter_that_is_not_important + 1) % 5;
			if (!misc_counter_that_is_not_important) {
				update_progress_form(media_usage_comment);
			}
			sleep(1);
		} else {
			// store set N
			sprintf(storing_filelist_fname, FILELIST_FNAME_RAW_SZ,
					bkpinfo->tmpdir, storing_set_no);
			sprintf(storing_afioball_fname, AFIOBALL_FNAME_RAW_SZ,
					bkpinfo->tmpdir, storing_set_no, bkpinfo->compression_suffix);
			if (g_getfattr) {
				sprintf(curr_xattr_list_fname, XATTR_LIST_FNAME_RAW_SZ,
					bkpinfo->tmpdir, storing_set_no);
			}
			if (g_getfacl) {
				sprintf(curr_acl_list_fname, ACL_LIST_FNAME_RAW_SZ,
					bkpinfo->tmpdir, storing_set_no);
			}

			mr_msg(2, "Storing set %d", storing_set_no);
			while (!does_file_exist(storing_filelist_fname)
				   || !does_file_exist(storing_afioball_fname)) {
				mr_msg(2,
						"Warning - either %s or %s doesn't exist yet. I'll pause 5 secs.",
						storing_filelist_fname, storing_afioball_fname);
				sleep(5);
			}
			strcpy(media_usage_comment, percent_media_full_comment());
			/* copy to CD (scratchdir) ... and an actual CD-R if necessary */
			if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
				register_in_tape_catalog(fileset, storing_set_no, -1,
										 storing_afioball_fname);
				maintain_collection_of_recent_archives(bkpinfo->tmpdir,
													   storing_afioball_fname);
				iamhere("Writing EXAT files");
				res += write_EXAT_files_to_tape(curr_xattr_list_fname,
												curr_acl_list_fname);
				// archives themselves
				res +=
					write_EXAT_files_to_tape(curr_xattr_list_fname,
											 curr_acl_list_fname);
				// archives themselves
				res +=
					move_files_to_stream(storing_afioball_fname,
										 NULL);
			} else {
				if (g_getfacl) {
					if (g_getfattr) {
						res = move_files_to_cd(storing_filelist_fname,
									 curr_xattr_list_fname,
									 curr_acl_list_fname,
									 storing_afioball_fname, NULL);
					} else {
						res = move_files_to_cd(storing_filelist_fname,
									curr_acl_list_fname,
									storing_afioball_fname, NULL);
					}
				} else {
					if (g_getfattr) {
							res = move_files_to_cd(storing_filelist_fname,
									curr_xattr_list_fname,
									storing_afioball_fname, NULL);
					} else {
							res = move_files_to_cd(storing_filelist_fname,
									storing_afioball_fname, NULL);
					}
				}
			}
			retval += res;
			g_current_progress++;
			update_progress_form(media_usage_comment);
			if (res) {
				mr_asprintf(&tmp,
						 "Failed to add archive %ld's files to CD dir\n",
						 storing_set_no);
				log_to_screen(tmp);
				mr_free(tmp);
				fatal_error
					("Is your hard disk full? If not, please send the author the logfile.");
			}
			storing_set_no++;
			//      sleep(2);
		}
	}
	close_progress_form();

	mr_msg(2, "Joining background threads to foreground thread");
	for (i = 0; i < noof_threads; i++) {
		pthread_join(archival_thread[i], pvp);
		mr_msg(3, "Thread %d of %d: closed OK", i + 1, noof_threads);
	}
	del_semvalue();
	mr_msg(2, "Done.");
	if (retval) {
		mr_asprintf(&tmp,
				 "Your regular files have been archived (with errors).");
	} else {
		mr_asprintf(&tmp,
				 "Your regular files have been archived successfully");
	}
	log_to_screen(tmp);
	mr_free(tmp);
	mr_free(transfer_block);
	mr_free(result_str);
	mr_free(storing_filelist_fname);
	mr_free(media_usage_comment);
	mr_free(storing_afioball_fname);
	mr_free(curr_xattr_list_fname);
	mr_free(curr_acl_list_fname);
	return (retval);
}


void pause_for_N_seconds(int how_long, char *msg)
{
	int i;
	open_evalcall_form(msg);
	for (i = 0; i < how_long; i++) {
		update_evalcall_form((int) ((100.0 / (float) (how_long) * i)));
		sleep(1);
	}
	close_evalcall_form();
}


/**
 * Create a USB image in @c destfile, from files in @c bkpinfo->scratchdir.
 *
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_media_type
 * - @c nonbootable_backup
 * - @c scratchdir
 *
 * @param destfile Where to put the generated USB image.
 * @return The number of errors encountered (0 for success)
 */
int make_usb_fs()
{
	/*@ int ********************************************** */
	int retval = 0;
	int res;

	/*@ buffers ****************************************** */
	char *tmp = NULL;
	char *tmp1 = NULL;
	char *result_sz = NULL;
	char *message_to_screen = NULL;
	char *old_pwd;

	malloc_string(old_pwd);
	assert(bkpinfo != NULL);

	log_msg(2, "make_usb_fs --- scratchdir=%s", bkpinfo->scratchdir);
	(void) getcwd(old_pwd, MAX_STR_LEN - 1);
	asprintf(&tmp, "chmod 755 %s", bkpinfo->scratchdir);
	run_program_and_log_output(tmp, FALSE);
	paranoid_free(tmp);
	chdir(bkpinfo->scratchdir);

	asprintf(&message_to_screen, "Copying data to make %s #%d",
				media_descriptor_string(bkpinfo->backup_media_type),
				g_current_media_number);
	log_msg(1, message_to_screen);

	asprintf(&tmp1, "%s1", bkpinfo->media_device);
	if (is_this_device_mounted(tmp1)) {
		log_msg(1, "USB device mounted. Remounting it at the right place");
		asprintf(&tmp, "umount %s", tmp1);
		run_program_and_log_output(tmp, FALSE);
		paranoid_free(tmp);
	}
	paranoid_free(tmp);

	log_msg(1, "Mounting USB device.");
	asprintf(&tmp1, "%s/usb", bkpinfo->tmpdir);
	asprintf(&tmp, "mkdir -p %s", tmp1);
	run_program_and_log_output(tmp, FALSE);
	paranoid_free(tmp);
	/* Mindi always create one single parition on the USB dev */
	asprintf(&tmp, "mount %s1 %s", bkpinfo->media_device, tmp1);
	run_program_and_log_output(tmp, FALSE);
	paranoid_free(tmp);

	if (bkpinfo->nonbootable_backup) {
		log_msg(1, "Making nonbootable USB backup not implemented yet");
	} else {
		log_msg(1, "Making bootable backup");

		/* Command to execute */
		asprintf(&tmp,"mv %s/* %s", bkpinfo->scratchdir, tmp1); 
		res = eval_call_to_make_USB(tmp, message_to_screen);
		if (res) {
			asprintf(&result_sz, "%s ...failed",tmp);
		} else {
			asprintf(&result_sz, "%s ...OK",tmp);
		}
		log_to_screen(result_sz);
		paranoid_free(result_sz);
		paranoid_free(tmp);
		retval += res;
	}
	paranoid_free(message_to_screen);
	paranoid_free(tmp1);

	if (is_this_device_mounted(bkpinfo->media_device)) {
		asprintf(&tmp, "umount %s1", bkpinfo->media_device);
		run_program_and_log_output(tmp, FALSE);
		paranoid_free(tmp);
	}

	chdir(old_pwd);
	if (retval) {
		log_msg(1, "WARNING - make_usb_fs returned an error");
	}
	paranoid_free(old_pwd);
	return (retval);
}


/**
 * Create an ISO image in @c destfile, from files in @c bkpinfo->scratchdir.
 *
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_media_type
 * - @c call_after_iso
 * - @c call_before_iso
 * - @c call_burn_iso
 * - @c call_make_iso
 * - @c manual_tray
 * - @c nonbootable_backup
 * - @c scratchdir
 *
 * @param destfile Where to put the generated ISO image.
 * @return The number of errors encountered (0 for success)
 */
int make_iso_fs(char *destfile)
{
	/*@ int ********************************************** */
	int retval = 0;
	int res;

	/*@ buffers ****************************************** */
	char *tmp = NULL;
	char *old_pwd;
	char *message_to_screen = NULL;
	char *sz_blank_disk = NULL;
	char *tmp2 = NULL;
	char *tmp3 = NULL;

	malloc_string(old_pwd);
	assert(bkpinfo != NULL);
	assert_string_is_neither_NULL_nor_zerolength(destfile);

	mr_asprintf(&tmp, "%s/isolinux.bin", bkpinfo->scratchdir);
	mr_asprintf(&tmp2, "%s/isolinux.bin", bkpinfo->tmpdir);
	if (does_file_exist(tmp)) {
		mr_asprintf(&tmp3, "cp -f %s %s", tmp, tmp2);
		paranoid_system(tmp3);
		mr_free(tmp3);
	}
	if (!does_file_exist(tmp) && does_file_exist(tmp2)) {
		mr_asprintf(&tmp3, "cp -f %s %s", tmp2, tmp);
		paranoid_system(tmp3);
		mr_free(tmp3);
	}
	mr_free(tmp2);
	mr_free(tmp);

	if (bkpinfo->backup_media_type != iso && bkpinfo->manual_tray) {
		popup_and_OK(_("Please insert new media and press Enter."));
	}

	mr_msg(2, "make_iso_fs --- scratchdir=%s --- destfile=%s",
			bkpinfo->scratchdir, destfile);
	/* BERLIOS: Do not ignore getcwd result */
	(void) getcwd(old_pwd, MAX_STR_LEN - 1);
	chmod(bkpinfo->scratchdir,0755);
	chdir(bkpinfo->scratchdir);

	if (bkpinfo->call_before_iso[0] != '\0') {
		mr_asprintf(&message_to_screen, "Running pre-ISO call for CD#%d",
				g_current_media_number);
		res = eval_call_to_make_ISO(bkpinfo->call_before_iso,
								destfile, g_current_media_number,
								MONDO_LOGFILE, message_to_screen);
		if (res) {
			log_to_screen("%s...failed", message_to_screen);
		} else {
			log_to_screen("%s...OK", message_to_screen);
		}
		mr_free(message_to_screen);
		retval += res;
	}

	if (bkpinfo->call_make_iso[0] != '\0') {
		mr_msg(2, "bkpinfo->call_make_iso = %s", bkpinfo->call_make_iso);
		mr_asprintf(&message_to_screen, "Making an ISO (%s #%d)",
				 bkpinfo->backup_media_string,
				 g_current_media_number);

		/* if g_current_media_number >= 2 then pause & ask */
		if (bkpinfo->backup_media_type != iso) {
			pause_and_ask_for_cdr(2);
		}
		if (retval) {
			log_to_screen
				("Serious error(s) occurred already. I shan't try to write to media.");
		} else {
			res = eval_call_to_make_ISO(bkpinfo->call_make_iso,
										destfile, g_current_media_number,
										MONDO_LOGFILE, message_to_screen);
			if (res) {
				log_to_screen("%s...failed to write", message_to_screen);
			} else {
				log_to_screen("%s...OK", message_to_screen);
				mr_asprintf(&tmp, "tail -n10 %s | grep -F ':-('", MONDO_LOGFILE);
				if (!run_program_and_log_output(tmp, 1)) {
					log_to_screen
						("Despite nonfatal errors, growisofs confirms the write was successful.");
				}
				mr_free(tmp);
			}
			retval += res;
#ifdef DVDRWFORMAT
			mr_asprintf(&tmp,
					 "tail -n8 %s | grep 'blank=full.*dvd-compat.*DAO'",
					 MONDO_LOGFILE);
			if (g_backup_media_type == dvd
				&& (res || !run_program_and_log_output(tmp, 1))) {
				log_to_screen
					("Failed to write to disk. I shall blank it and then try again.");
				sleep(5);
				sync();
				pause_for_N_seconds(5, "Letting DVD drive settle");

				// dvd+rw-format --- OPTION 2
				if (!bkpinfo->please_dont_eject) {
					log_to_screen("Ejecting media to clear drive status.");
					eject_device(bkpinfo->media_device);
					inject_device(bkpinfo->media_device);
				}
				pause_for_N_seconds(5, "Letting DVD drive settle");
				mr_asprintf(&sz_blank_disk, "dvd+rw-format -force %s",
						 bkpinfo->media_device);
				mr_msg(3, "sz_blank_disk = '%s'", sz_blank_disk);
				res = run_external_binary_with_percentage_indicator_NEW
					("Blanking DVD disk", sz_blank_disk);
				if (res) {
					log_to_screen
						("Warning - format failed. (Was it a DVD-R?) Sleeping for 5 seconds to take a breath...");
					pause_for_N_seconds(5,
										"Letting DVD drive settle... and trying again.");
					res = run_external_binary_with_percentage_indicator_NEW
						("Blanking DVD disk", sz_blank_disk);
					if (res) {
						log_to_screen("Format failed a second time.");
					}
				} else {
					log_to_screen
						("Format succeeded. Sleeping for 5 seconds to take a breath...");
				}
				mr_free(sz_blank_disk);
				pause_for_N_seconds(5, "Letting DVD drive settle");
				if (!bkpinfo->please_dont_eject) {
					log_to_screen("Ejecting media to clear drive status.");
					eject_device(bkpinfo->media_device);
					inject_device(bkpinfo->media_device);
				}
				pause_for_N_seconds(5, "Letting DVD drive settle");
				res =
					eval_call_to_make_ISO(bkpinfo->call_make_iso,
										  destfile,
										  g_current_media_number,
										  MONDO_LOGFILE,
										  message_to_screen);
				retval += res;
				if (!bkpinfo->please_dont_eject) {
					log_to_screen("Ejecting media.");
					eject_device(bkpinfo->media_device);
				}
				if (res) {
					log_to_screen("Dagnabbit. It still failed.");
				} else {
					log_to_screen
						("OK, this time I successfully backed up to DVD.");
				}
			}
			mr_free(tmp);
#endif
			if (g_backup_media_type == dvd && !bkpinfo->please_dont_eject) {
				eject_device(bkpinfo->media_device);
			}
		}
		mr_free(message_to_screen);
	} else {
		fatal_error("call_make_iso undefined. Not normal in this case");
	}

	if (bkpinfo->backup_media_type == cdr
		|| bkpinfo->backup_media_type == cdrw) {
		if (is_this_device_mounted(bkpinfo->media_device)) {
			mr_msg(2,
					"Warning - %s mounted. I'm unmounting it before I burn to it.",
					bkpinfo->media_device);
			mr_asprintf(&tmp, "umount %s", bkpinfo->media_device);
			run_program_and_log_output(tmp, FALSE);
			mr_free(tmp);
		}
	}

	if (bkpinfo->call_after_iso != NULL) {
		mr_asprintf(&message_to_screen, "Running post-ISO call (%s #%d)",
				 bkpinfo->backup_media_string,
				 g_current_media_number);
		res = eval_call_to_make_ISO(bkpinfo->call_after_iso,
									destfile, g_current_media_number,
									MONDO_LOGFILE, message_to_screen);
		if (res) {
			log_to_screen("%s...failed", message_to_screen);
		} else {
			log_to_screen("%s...OK", message_to_screen);
		}
		mr_free(message_to_screen);
		retval += res;
	}

	chdir(old_pwd);
	if (retval) {
		mr_msg(1, "WARNING - make_iso_fs returned an error");
	}
	mr_free(old_pwd);
	return (retval);
}


bool is_dev_an_NTFS_dev(char *bigfile_fname)
{
	char *tmp;
	char *command;
	malloc_string(tmp);
	bool ret = TRUE;
	mr_asprintf(&command,
			 "dd if=%s bs=512 count=1 2> /dev/null | strings | head -n1",
			 bigfile_fname);
	mr_msg(1, "command = '%s'", command);
	strcpy(tmp, call_program_and_get_last_line_of_output(command));
	mr_msg(1, "--> tmp = '%s'", tmp);
	mr_free(command);
	if (strstr(tmp, "NTFS")) {
		iamhere("TRUE");
	} else {
		iamhere("FALSE");
		ret = FALSE;
	}
	return(ret);
}


/**
 * Back up big files by chopping them up.
 * This function backs up all "big" files (where "big" depends
 * on your backup media) in "chunks" (whose size again depends
 * on your media).
 *
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_media_type
 * - @c optimal_set_size
 * @param biggielist_fname The path to a file containing a list of
 * all "big" files.
 * @return The number of errors encountered (0 for success)
 * @see slice_up_file_etc
 */
int
make_slices_and_images(char *biggielist_fname)
{

	/*@ pointers ******************************************* */
	FILE *fin = NULL;
	char *p = NULL;

	/*@ buffers ******************************************** */
	char *tmp = NULL;
	char *bigfile_fname = NULL;
	char *sz_devfile = NULL;
	char *ntfsprog_fifo = NULL;
	/*@ long *********************************************** */
	long biggie_file_number = 0;
	long noof_biggie_files = 0;
	long estimated_total_noof_slices = 0;

	/*@ int ************************************************ */
	int retval = 0;
	int res = 0;
	size_t n = 0;
	pid_t pid;
	FILE *ftmp = NULL;
	bool delete_when_done;
	bool use_ntfsprog;
	off_t biggie_fsize;

	assert(bkpinfo != NULL);
	assert_string_is_neither_NULL_nor_zerolength(biggielist_fname);

	estimated_total_noof_slices =
		size_of_all_biggiefiles_K() / bkpinfo->optimal_set_size + 1;

	mr_msg(1, "size of all biggiefiles = %ld",
			size_of_all_biggiefiles_K());
	mr_msg(1, "estimated_total_noof_slices = %ld KB / %ld KB = %ld",
			size_of_all_biggiefiles_K(), bkpinfo->optimal_set_size,
			estimated_total_noof_slices);

	if (length_of_file(biggielist_fname) < 6) {
		mr_msg(1, "No biggiefiles; fair enough...");
		return (0);
	}
	mr_asprintf(&tmp, "I am now backing up all large files.");
	log_to_screen(tmp);
	noof_biggie_files = count_lines_in_file(biggielist_fname);
	open_progress_form("Backing up big files", tmp,
					   "Please wait. This may take some time.", "",
					   estimated_total_noof_slices);
	mr_free(tmp);

	if (!(fin = fopen(biggielist_fname, "r"))) {
		log_OS_error("Unable to openin biggielist");
		return (1);
	}
	for (mr_getline(&bigfile_fname, &n, fin); !feof(fin);
		 mr_getline(&bigfile_fname, &n, fin), biggie_file_number++) {
		use_ntfsprog = FALSE;
		if (bigfile_fname[strlen(bigfile_fname) - 1] < 32) {
			bigfile_fname[strlen(bigfile_fname) - 1] = '\0';
		}
		biggie_fsize = length_of_file(bigfile_fname);
		delete_when_done = FALSE;

		if (!does_file_exist(bigfile_fname)) {
			ftmp = fopen(bigfile_fname, "w");
			if (ftmp == NULL) {
				mr_msg(3, "Unable to write to %s", bigfile_fname);
				// So skip it as it doesn't exist
				continue;
			} else {
				paranoid_fclose(ftmp);
			}
			delete_when_done = TRUE;
		} else {
			// Call ntfsclone (formerly partimagehack) if it's a /dev entry 
			// (i.e. a partition to be imaged)
			mr_msg(2, "bigfile_fname = %s", bigfile_fname);
			use_ntfsprog = FALSE;
			if (!strncmp(bigfile_fname, "/dev/", 5)
				&& is_dev_an_NTFS_dev(bigfile_fname)) {
				use_ntfsprog = TRUE;
				mr_msg(2,
						"Calling ntfsclone in background because %s is an NTFS partition",
						bigfile_fname);
				mr_asprintf(&sz_devfile, "%s/%d.%d.000",
						bkpinfo->tmpdir,
						(int) (random() % 32768),
						(int) (random() % 32768));
				mkfifo(sz_devfile, 0x770);
				ntfsprog_fifo = sz_devfile;
				switch (pid = fork()) {
				case -1:
					fatal_error("Fork failure");
				case 0:
					mr_msg(2,
							"CHILD - fip - calling feed_into_ntfsprog(%s, %s)",
							bigfile_fname, sz_devfile);
					res = feed_into_ntfsprog(bigfile_fname, sz_devfile);
					mr_free(sz_devfile);
					exit(res);
					break;
				default:
					mr_msg(2,
							"feed_into_ntfsprog() called in background --- pid=%ld",
							(long int) (pid));
					mr_free(sz_devfile);
					break;
				}
			}
			// Otherwise, use good old 'dd' and 'bzip2'
			else {
				ntfsprog_fifo = NULL;
			}

			// Whether partition or biggiefile, just do your thang :-)
			mr_msg(5, "Bigfile #%ld is '%s' (%ld KB)",
					biggie_file_number + 1, bigfile_fname,
					(long) biggie_fsize >> 10);
			if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
				write_header_block_to_stream(biggie_fsize, bigfile_fname,
											 use_ntfsprog ?
											 BLK_START_A_PIHBIGGIE :
											 BLK_START_A_NORMBIGGIE);
			}
			res =
				slice_up_file_etc(bigfile_fname,
								  ntfsprog_fifo, biggie_file_number,
								  noof_biggie_files, use_ntfsprog);
			if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
				write_header_block_to_stream((off_t)0,
											 calc_checksum_of_file
											 (bigfile_fname),
											 BLK_STOP_A_BIGGIE);
			}
			retval += res;
			p = strrchr(bigfile_fname, '/');
			if (p) {
				p++;
			} else {
				p = bigfile_fname;
			}
			if (res) {
				mr_asprintf(&tmp, "Archiving %s ... Failed!", bigfile_fname);
			} else {
				mr_asprintf(&tmp, "Archiving %s ... OK!", bigfile_fname);
			}
			mr_msg(4,tmp);
			mr_free(tmp);
			if (delete_when_done) {
				unlink(bigfile_fname);
				delete_when_done = FALSE;
			}
		}
		if (!g_text_mode) {
			newtDrawRootText(0, g_noof_rows - 2, tmp);
			newtRefresh();
		}
	}
	mr_free(bigfile_fname);
	paranoid_fclose(fin);

	mr_msg(1, "Finished backing up bigfiles");
	mr_msg(1, "estimated slices = %ld; actual slices = %ld",
			estimated_total_noof_slices, g_current_progress);
	close_progress_form();
	return (retval);
}


/**
 * Single-threaded version of @c make_afioballs_and_images().
 * @see make_afioballs_and_images
 */
int make_afioballs_and_images_OLD()
{

	/*@ int ************************************************** */
	int retval = 0;
	long int curr_set_no = 0;
	int res = 0;

	/*@ buffers ********************************************** */
	char *curr_filelist_fname = NULL;
	char *curr_afioball_fname = NULL;
	char *curr_xattr_list_fname = NULL;
	char *curr_acl_list_fname = NULL;
	char *media_usage_comment = NULL;
	char *tmp= mr_malloc(MAX_STR_LEN * 2);

	/* BERLIOS: Useless ?
	   mr_asprintf(&tmp, "%s/archives/filelist.full", bkpinfo->scratchdir);
	 */
	malloc_string(media_usage_comment);
	log_to_screen("Archiving regular files");

	open_progress_form(_("Backing up filesystem"),
					   _("I am backing up your live filesystem now."),
					   _("Please wait. This may take a couple of hours."),
					   _("Working..."),
					   get_last_filelist_number() + 1);

	mr_asprintf(&curr_filelist_fname, FILELIST_FNAME_RAW_SZ, bkpinfo->tmpdir,
			 0L);

	curr_set_no = 0;
	while (does_file_exist(curr_filelist_fname)) {
		/* backup this set of files */
		mr_asprintf(&curr_afioball_fname, AFIOBALL_FNAME_RAW_SZ,
				 bkpinfo->tmpdir, curr_set_no, bkpinfo->compression_suffix);

		mr_msg(1, "EXAT'g set %ld", curr_set_no);
		if (g_getfattr) {
			mr_asprintf(&curr_xattr_list_fname, XATTR_LIST_FNAME_RAW_SZ,
				bkpinfo->tmpdir, curr_set_no);
			get_fattr_list(curr_filelist_fname, curr_xattr_list_fname);
		}
		if (g_getfacl) {
			mr_asprintf(&curr_acl_list_fname, ACL_LIST_FNAME_RAW_SZ,
				bkpinfo->tmpdir, curr_set_no);
			get_acl_list(curr_filelist_fname, curr_acl_list_fname);
		}

		mr_msg(1, "Archiving set %ld", curr_set_no);
		res = archive_this_fileset(curr_filelist_fname,
								 curr_afioball_fname, curr_set_no);
		retval += res;
		if (res) {
			mr_asprintf(&tmp,
					 "Errors occurred while archiving set %ld. Perhaps your live filesystem changed?",
					 curr_set_no);
			log_to_screen(tmp);
			mr_free(tmp);
		}

		strcpy(media_usage_comment, percent_media_full_comment());

		/* copy to CD (scratchdir) ... and an actual CD-R if necessary */
		if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
			register_in_tape_catalog(fileset, curr_set_no, -1, curr_afioball_fname);
			maintain_collection_of_recent_archives(bkpinfo->tmpdir, curr_afioball_fname);
			iamhere("Writing EXAT files");
			res +=
				write_EXAT_files_to_tape(curr_xattr_list_fname,
										 curr_acl_list_fname);
			// archives themselves
			res = move_files_to_stream(curr_afioball_fname, NULL);
		} else {
				if (g_getfacl) {
					if (g_getfattr) {
						res = move_files_to_cd(curr_filelist_fname,
									 curr_xattr_list_fname,
									 curr_acl_list_fname,
									 curr_afioball_fname, NULL);
					} else {
						res = move_files_to_cd(curr_filelist_fname,
									curr_acl_list_fname,
									curr_afioball_fname, NULL);
					}
				} else {
					if (g_getfattr) {
							res = move_files_to_cd(curr_filelist_fname,
									curr_xattr_list_fname,
									curr_afioball_fname, NULL);
					} else {
							res = move_files_to_cd(curr_filelist_fname,
									curr_afioball_fname, NULL);
					}
				}
		}
		retval += res;
		g_current_progress++;
		update_progress_form(media_usage_comment);

		if (res) {
			mr_asprintf(&tmp, "Failed to add archive %ld's files to CD dir\n",
					 curr_set_no);
			log_to_screen(tmp);
			mr_free(tmp);
			fatal_error
				("Is your hard disk is full? If not, please send the author the logfile.");
		}
		mr_free(curr_filelist_fname);
		mr_free(curr_afioball_fname);
		mr_free(curr_xattr_list_fname);
		mr_free(curr_acl_list_fname);
		mr_asprintf(&curr_filelist_fname, FILELIST_FNAME_RAW_SZ,
				 bkpinfo->tmpdir, ++curr_set_no);
	}
	mr_free(curr_filelist_fname);
	close_progress_form();
	if (retval) {
		log_to_screen
			("Your regular files have been archived (with errors).");
	} else {
		log_to_screen
			("Your regular files have been archived successfully.");
	}
	mr_free(media_usage_comment);
	return (retval);
}

/* @} - end of LLarchiveGroup */


/**
 * Wrapper around @c make_afioballs_and_images().
 * @param bkpinfo the backup information structure. Only the
 * @c backup_media_type field is used within this function.
 * @return return code of make_afioballs_and_images
 * @see make_afioballs_and_images
 * @ingroup MLarchiveGroup
 */
int make_those_afios_phase()
{
	/*@ int ******************************************* */
	int res = 0;
	int retval = 0;

	assert(bkpinfo != NULL);

	mvaddstr_and_log_it(g_currentY, 0,
						"Archiving regular files to media          ");

	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		write_header_block_to_stream((off_t)0, "start-of-afioballs",
									 BLK_START_AFIOBALLS);
#if __FreeBSD__ == 5
		mr_msg(1,
				"Using single-threaded make_afioballs_and_images() to suit b0rken FreeBSD 5.0");
		res = make_afioballs_and_images_OLD();
#else
		res = make_afioballs_and_images_OLD();
#endif
		write_header_block_to_stream((off_t)0, "stop-afioballs",
									 BLK_STOP_AFIOBALLS);
	} else {
		res = make_afioballs_and_images();
	}

	retval += res;
	if (res) {
		mvaddstr_and_log_it(g_currentY++, 74, "Errors.");
		mr_msg(1, "make_afioballs_and_images returned an error");
	} else {
		mvaddstr_and_log_it(g_currentY++, 74, "Done.");
	}
	return (retval);
}

/**
 * Wrapper around @c make_slices_and_images().
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_media_type
 * - @c scratchdir
 * - @c tmpdir
 * @return The number of errors encountered (0 for success)
 * @ingroup MLarchiveGroup
 */
int make_those_slices_phase()
{

	/*@ int ***************************************************** */
	int res = 0;
	int retval = 0;

	/*@ buffers ************************************************** */
	char *biggielist = NULL;
	char *command = NULL;
	char *blah = NULL;
	char *xattr_fname = NULL;
	char *acl_fname = NULL;

	assert(bkpinfo != NULL);
	/* slice big files */
	mvaddstr_and_log_it(g_currentY, 0,
						"Archiving large files to media           ");
	mr_asprintf(&biggielist, "%s/archives/biggielist.txt", bkpinfo->scratchdir);
	if (g_getfattr) {
		mr_asprintf(&xattr_fname, XATTR_BIGGLST_FNAME_RAW_SZ, bkpinfo->tmpdir);
	}
	if (g_getfacl) {
		mr_asprintf(&acl_fname, ACL_BIGGLST_FNAME_RAW_SZ, bkpinfo->tmpdir);
	}

	mr_asprintf(&command, "cp %s/biggielist.txt %s", bkpinfo->tmpdir, biggielist);
	paranoid_system(command);
	mr_free(command);

	mr_asprintf(&blah, "biggielist = %s", biggielist);
	mr_msg(2, blah);
	mr_free(blah);

	if (!does_file_exist(biggielist)) {
		mr_msg(1, "BTW, the biggielist does not exist");
	}

	if (g_getfattr) {
		get_fattr_list(biggielist, xattr_fname);
		mr_asprintf(&command, "cp %s %s/archives/", xattr_fname, bkpinfo->scratchdir);
		paranoid_system(command);
		mr_free(command);
	}
	if (g_getfacl) {
		get_acl_list(biggielist, acl_fname);
		mr_asprintf(&command, "cp %s %s/archives/", acl_fname, bkpinfo->scratchdir);
		paranoid_system(command);
		mr_free(command);
	}

	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		res += write_EXAT_files_to_tape(xattr_fname, acl_fname);
		mr_asprintf(&blah, "%ld", count_lines_in_file(biggielist));
		write_header_block_to_stream((off_t)0, blah, BLK_START_BIGGIEFILES);
		mr_free(blah);
	}
	if (g_getfattr) {
		mr_free(xattr_fname);
	}
	if (g_getfacl) {
		mr_free(acl_fname);
	}

	res = make_slices_and_images(biggielist);
	mr_free(biggielist);

	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		write_header_block_to_stream((off_t)0, "end-of-biggiefiles",
									 BLK_STOP_BIGGIEFILES);
	}
	retval += res;
	if (res) {
		mr_msg(1, "make_slices_and_images returned an error");
		mvaddstr_and_log_it(g_currentY++, 74, "Errors.");
	} else {
		mvaddstr_and_log_it(g_currentY++, 74, "Done.");
	}
	return (retval);
}


/**
 * @addtogroup LLarchiveGroup
 * @{
 */
/**
 * Function pointer to an appropriate @c move_files_to_cd routine.
 * You can set this to your own function (for example, one to
 * transfer files over the network) or leave it as is.
 */
int (*move_files_to_cd) (char *, ...) =
	_move_files_to_cd;

/**
 * Move some files to the ISO scratch directory.
 * This function moves files specified as parameters, into the directory
 * @c bkpinfo->scratchdir, where the files that will be stored on the next
 * CD are waiting.
 *
 * @param bkpinfo The backup information structure. Fields used:
 * - @c media_size
 * - @c scratchdir
 * @param files_to_add The files to add to the scratchdir.
 * @warning The list of @c files_to_add must be terminated with @c NULL.
 * @note If and when the space occupied by the scratchdir would exceed
 * the capacity of the current CD,
 * <tt>write_iso_and_go_on(bkpinfo, FALSE)</tt> is called and the
 * scratchdir is emptied.
 *
 * @return The number of errors encountered (0 for success)
 */
int _move_files_to_cd(char *files_to_add, ...)
{

	/*@ int ************************************************************ */
	int retval = 0;
	int res = 0;

	/*@ buffers ******************************************************** */
	char *tmp = NULL;
	char *curr_file = NULL;
	char *cf = NULL;

	/*@ long ************************************************************ */
	va_list ap;
	long long would_occupy;

	assert(bkpinfo != NULL);
	would_occupy = space_occupied_by_cd(bkpinfo->scratchdir);
	va_start(ap, files_to_add);	// initialize the variable arguments
	for (cf = files_to_add; cf != NULL; cf = va_arg(ap, char *)) {
		if (!cf) {
			continue;
		}
		mr_asprintf(&curr_file, cf);
		if (!does_file_exist(curr_file)) {
			mr_msg(1,
					"Warning - you're trying to add a non-existent file - '%s' to the CD",
					curr_file);
		} else {
			mr_msg(8, "Trying to add file %s to CD", curr_file);
			would_occupy += length_of_file(curr_file) / 1024;
		}
		mr_free(curr_file);
	}
	va_end(ap);

	if (bkpinfo->media_size <= 0L) {
		fatal_error("move_files_to_cd() - unknown media size");
	}
	if (would_occupy / 1024 > bkpinfo->media_size) {
		/* FALSE because this is not the last CD we'll write */
		res = write_iso_and_go_on(FALSE);
		retval += res;
		if (res) {
			mr_msg(1, "WARNING - write_iso_and_go_on returned an error");
		}
	}

	va_start(ap, files_to_add);	// initialize the variable arguments
	for (cf = files_to_add; cf != NULL; cf = va_arg(ap, char *)) {
		if (!cf) {
			continue;
		}
		mr_asprintf(&curr_file, cf);

		mr_asprintf(&tmp, "mv -f %s %s/archives/", curr_file,
				 bkpinfo->scratchdir);
		res = run_program_and_log_output(tmp, 5);
		retval += res;
		if (res) {
			mr_msg(1, "(move_files_to_cd) '%s' failed", tmp);
		} else {
			mr_msg(8, "Moved %s to CD OK", tmp);
		}
		mr_free(tmp);
		mr_free(curr_file);
		//      unlink (curr_file);
	}
	va_end(ap);

	if (retval) {
		mr_msg(1,
				"Warning - errors occurred while I was adding files to CD dir");
	}
	return (retval);
}

/* @} - end of LLarchiveGroup */


/**
 * @addtogroup LLarchiveGroup
 * @{
 */
/**
 * Function pointer to an appropriate @c move_files_to_stream routine.
 * You can set this to your own function (for example, one to
 * transfer files over the network) or leave it as is.
 */
int (*move_files_to_stream) (char *, ...) =
	_move_files_to_stream;

/**
 * Copy some files to tape.
 * This function copies the files specified as parameters into the tape stream.
 *
 * @param bkpinfo The backup information structure. Used only in the call to
 * @c write_file_to_stream_from_file().
 *
 * @param files_to_add The files to copy to the tape stream.
 * @warning The list of @c files_to_add must be terminated with @c NULL.
 * @note Files may be split across multiple tapes if necessary.
 *
 * @return The number of errors encountered (0 for success)
 */
int
_move_files_to_stream(char *files_to_add, ...)
{

	/*@ int ************************************************************ */
	int retval = 0;
	int res = 0;
	/*@ buffers ******************************************************** */

	/*@ char *********************************************************** */
	char start_chr;
	char stop_chr;
	char *curr_file = NULL;
	char *cf = NULL;
	/*@ long long ****************************************************** */
	off_t length_of_incoming_file = (off_t)0;
	t_archtype type;
	va_list ap;

	assert(bkpinfo != NULL);
	va_start(ap, files_to_add);
	for (cf = files_to_add; cf != NULL; cf = va_arg(ap, char *)) {
		if (!cf) {
			continue;
		}
		mr_asprintf(&curr_file, cf);
		if (!does_file_exist(curr_file)) {
			mr_msg(1,
					"Warning - you're trying to add a non-existent file - '%s' to the tape",
					curr_file);
		}
		/* create header chars */
		start_chr = BLK_START_AN_AFIO_OR_SLICE;
		stop_chr = BLK_STOP_AN_AFIO_OR_SLICE;
		/* ask for new tape if necessary */
		length_of_incoming_file = length_of_file(curr_file);
		write_header_block_to_stream(length_of_incoming_file, curr_file,
									 start_chr);
		if (strstr(curr_file, ".afio.") || strstr(curr_file, ".star.")) {
			type = fileset;
		} else if (strstr(curr_file, "slice")) {
			type = biggieslice;
		} else {
			type = other;
		}
		res = write_file_to_stream_from_file(curr_file);
		retval += res;
		unlink(curr_file);
		mr_free(curr_file);
		/* write closing header */
		write_header_block_to_stream((off_t)0, "finished-writing-file", stop_chr);
	}
	va_end(ap);

	if (retval) {
		mr_msg(1,
				"Warning - errors occurred while I was adding file to tape");
	}
	return (retval);
}

/* @} - end of LLarchiveGroup */


/**
 * @addtogroup utilityGroup
 * @{
 */
/**
 * Make sure the user has a valid CD-R(W) in the CD drive.
 * @param cdrw_dev Set to the CD-R(W) device checked.
 * @param keep_looping If TRUE, keep pestering user until they insist
 * or insert a correct CD; if FALSE, only check once.
 * @return 0 (there was an OK CD in the drive) or 1 (there wasn't).
 */
int interrogate_disk_currently_in_cdrw_drive(char *cdrw_dev,
											 bool keep_looping)
{
	int res = 0;
	char *bkp = NULL;
	char *cdrecord = NULL;

	malloc_string(bkp);
	strcpy(bkp, cdrw_dev);
	if (find_cdrw_device(cdrw_dev)) {
		strcpy(cdrw_dev, bkp);
	} else {
		if (!system("which cdrecord > /dev/null 2> /dev/null")) {
			mr_asprintf(&cdrecord, "cdrecord dev=%s -atip", cdrw_dev);
		} else if (!system("which dvdrecord > /dev/null 2> /dev/null")) {
			mr_asprintf(&cdrecord, "dvdrecord dev=%s -atip", cdrw_dev);
		} else {
			mr_msg(2, "Oh well. I guess I'll just pray then.");
		}
		if (cdrecord != NULL) {
			if (!keep_looping) {
				retract_CD_tray_and_defeat_autorun();
				res = run_program_and_log_output(cdrecord, 5);
			} else {
				while ((res = run_program_and_log_output(cdrecord, 5))) {
					retract_CD_tray_and_defeat_autorun();
					if (ask_me_yes_or_no
						("Unable to examine CD. Are you sure this is a valid CD-R(W) CD?"))
					{
						mr_msg(1, "Well, he insisted...");
						break;
					}
				}
			}
		}
		mr_free(cdrecord);
	}
//  retract_CD_tray_and_defeat_autorun();
	mr_free(bkp);
	return (res);
}


/**
 * Asks the user to put a CD-R(W) in the drive.
 * @param ask_for_one_if_more_than_this (unused)
 */
void
pause_and_ask_for_cdr(int ask_for_one_if_more_than_this)
{

	/*@ buffers ********************************************* */
	char *tmp = NULL;
	char *szmsg = NULL;
	char *cdrom_dev = NULL;
	char *cdrw_dev = NULL;
	char *our_serial_str = NULL;
	bool ok_go_ahead_burn_it;
	int cd_number = -1;
	int attempt_to_mount_returned_this = 999;
	char *mtpt = NULL;
	char *szcdno = NULL;
	char *szserfname = NULL;
	char *szunmount = NULL;

	malloc_string(szmsg);
	malloc_string(cdrom_dev);
	malloc_string(cdrw_dev);
	malloc_string(mtpt);
	malloc_string(szcdno);
	malloc_string(szserfname);
	malloc_string(our_serial_str);
	malloc_string(szunmount);

	sprintf(szmsg, "I am about to burn %s #%d",
			media_descriptor_string(g_backup_media_type),
			g_current_media_number);
	log_to_screen(szmsg);
	if (g_current_media_number < ask_for_one_if_more_than_this) {
		return;
	}
	log_to_screen("Scanning CD-ROM drive...");
	sprintf(mtpt, "%s/cd.mtpt", bkpinfo->tmpdir);
	make_hole_for_dir(mtpt);

  gotos_make_me_puke:
	ok_go_ahead_burn_it = TRUE;
	if (!find_cdrom_device(cdrom_dev, FALSE)) {
/* When enabled, it made CD eject-and-retract when wrong CD inserted.. Weird
      mr_msg(2, "paafcd: Retracting CD-ROM drive if possible" );
      retract_CD_tray_and_defeat_autorun();
*/
		mr_asprintf(&tmp, "umount %s", cdrom_dev);
		run_program_and_log_output(tmp, 1);
		mr_free(tmp);
		sprintf(szcdno, "%s/archives/THIS-CD-NUMBER", mtpt);
		sprintf(szserfname, "%s/archives/SERIAL-STRING", mtpt);
		sprintf(szunmount, "umount %s", mtpt);
		cd_number = -1;
		our_serial_str[0] = '\0';
		mr_asprintf(&tmp, "mount %s %s", cdrom_dev, mtpt);
		attempt_to_mount_returned_this = run_program_and_log_output(tmp, 1);
		mr_free(tmp);
		if (attempt_to_mount_returned_this) {
			mr_msg(4, "Failed to mount %s at %s", cdrom_dev, mtpt);
			log_to_screen("If there's a CD/DVD in the drive, it's blank.");
		} else if (!does_file_exist(szcdno)
				   || !does_file_exist(szserfname)) {
			log_to_screen
				("%s has data on it but it's probably not a Mondo CD.",
				 media_descriptor_string(g_backup_media_type));
		} else {
			log_to_screen("%s found in drive. It's a Mondo disk.",
						  media_descriptor_string(g_backup_media_type));
			cd_number = atoi(last_line_of_file(szcdno));
			mr_asprintf(&tmp, "cat %s 2> /dev/null", szserfname);
			strcpy(our_serial_str,
				   call_program_and_get_last_line_of_output(tmp));
			mr_free(tmp);
			// FIXME - should be able to use last_line_of_file(), surely?
		}
		run_program_and_log_output(szunmount, 1);
		mr_msg(2, "paafcd: cd_number = %d", cd_number);
		mr_msg(2, "our serial str = %s; g_serial_string = %s",
				our_serial_str, g_serial_string);
		if (cd_number > 0 && !strcmp(our_serial_str, g_serial_string)) {
			mr_msg(2, "This %s is part of this backup set!",
					media_descriptor_string(g_backup_media_type));
			ok_go_ahead_burn_it = FALSE;
			if (cd_number == g_current_media_number - 1) {
				log_to_screen
					("I think you've left the previous %s in the drive.",
					 media_descriptor_string(g_backup_media_type));
			} else {
				log_to_screen
					("Please remove this %s. It is part of the backup set you're making now.",
					 media_descriptor_string(g_backup_media_type));
			}
		} else {
			log_to_screen("...but not part of _our_ backup set.");
		}
	} else {
		mr_msg(2,
				"paafcd: Can't find CD-ROM drive. Perhaps it has a blank %s in it?",
				media_descriptor_string(g_backup_media_type));
		if (interrogate_disk_currently_in_cdrw_drive(cdrw_dev, FALSE)) {
			ok_go_ahead_burn_it = FALSE;
			log_to_screen("There isn't a writable %s in the drive.",
						  media_descriptor_string(g_backup_media_type));
		}
	}

	if (!ok_go_ahead_burn_it) {
		eject_device(cdrom_dev);
		mr_asprintf(&tmp,
				"I am about to burn %s #%d of the backup set. Please insert %s and press Enter.",
				media_descriptor_string(g_backup_media_type),
				g_current_media_number,
				media_descriptor_string(g_backup_media_type));
		popup_and_OK(tmp);
		mr_free(tmp);
		goto gotos_make_me_puke;
	} else {
		mr_msg(2, "paafcd: OK, going ahead and burning it.");
	}

	mr_msg(2,
			"paafcd: OK, I assume I have a blank/reusable %s in the drive...",
			media_descriptor_string(g_backup_media_type));

	//  if (ask_for_one_if_more_than_this>1) { popup_and_OK(szmsg); }

	log_to_screen("Proceeding w/ %s in drive.",
				  media_descriptor_string(g_backup_media_type));
	mr_free(szmsg);
	mr_free(cdrom_dev);
	mr_free(cdrw_dev);
	mr_free(mtpt);
	mr_free(szcdno);
	mr_free(szserfname);
	mr_free(our_serial_str);
	mr_free(szunmount);
}


/**
 * Set the <tt>N</tt>th bit of @c array to @c true_or_false.
 * @param array The bit array (as a @c char pointer).
 * @param N The bit number to set or reset.
 * @param true_or_false If TRUE then set bit @c N, if FALSE then reset bit @c N.
 * @see get_bit_N_of_array
 */
void set_bit_N_of_array(char *array, int N, bool true_or_false)
{
	int bit_number;
	int mask, orig_val, to_add;
	int element_number;

	assert(array != NULL);

	element_number = N / 8;
	bit_number = N % 8;
	to_add = (1 << bit_number);
	mask = 255 - to_add;
	orig_val = array[element_number] & mask;
	//  log_it("array[%d]=%02x; %02x&%02x = %02x", element_number, array[element_number], mask, orig_val);
	if (true_or_false) {
		array[element_number] = orig_val | to_add;
	}
}

/* @} - end of utilityGroup */


/**
 * Chop up @c filename.
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_media_type
 * - @c compression_level
 * - @c optimal_set_size
 * - @c tmpdir
 * - @c use_lzo
 * - @c compression_tool
 * - @c compression_suffix
 *
 * @param biggie_filename The file to chop up.
 * @param ntfsprog_fifo The FIFO to ntfsclone if this is an imagedev, NULL otherwise.
 * @param biggie_file_number The sequence number of this biggie file (starting from 0).
 * @param noof_biggie_files The number of biggie files there are total.
 * @return The number of errors encountered (0 for success)
 * @see make_slices_and_images
 * @ingroup LLarchiveGroup
 */
int
slice_up_file_etc(char *biggie_filename,
				  char *ntfsprog_fifo, long biggie_file_number,
				  long noof_biggie_files, bool use_ntfsprog)
{

	/*@ buffers ************************************************** */
	char *tmp = NULL;
	char *checksum_line = NULL;
	char *command = NULL;
	char *tempblock = NULL;
	char *curr_slice_fname_uncompressed = NULL;
	char *curr_slice_fname_compressed = NULL;
	char *file_to_archive = NULL;
	char *file_to_openin = NULL;
	/*@ pointers ************************************************** */
	char *pB = NULL;
	FILE *fin = NULL;
	FILE *fout = NULL;

	/*@ bool ****************************************************** */
	bool finished = FALSE;

	/*@ long ****************************************************** */
	size_t blksize = 0;
	long slice_num = 0;
	long i;
	long optimal_set_size;
	bool should_I_compress_slices;
	char *suffix = NULL;				// for compressed slices

	/*@ long long ************************************************** */
	off_t totalread = (off_t)0;
	off_t totallength = (off_t)0;
	off_t length;

	/*@ int ******************************************************** */
	int retval = 0;
	int res = 0;
	size_t n = 0;

	/*@ structures ************************************************** */
	struct s_filename_and_lstat_info biggiestruct;
//  struct stat statbuf;

	assert(bkpinfo != NULL);
	assert_string_is_neither_NULL_nor_zerolength(biggie_filename);

	biggiestruct.for_backward_compatibility = '\n';
	biggiestruct.use_ntfsprog = use_ntfsprog;
	optimal_set_size = bkpinfo->optimal_set_size;

	if (optimal_set_size < 999) {
		fatal_error("bkpinfo->optimal_set_size is insanely small");
	}
	if (ntfsprog_fifo) {
		file_to_openin = ntfsprog_fifo;
		mr_asprintf(&checksum_line, "IGNORE");
		mr_msg(2,
				"Not calculating checksum for %s: it would take too long",
				biggie_filename);
		if ( !find_home_of_exe("ntfsresize")) {
			fatal_error("ntfsresize not found");
		}
		mr_asprintf(&command, "ntfsresize --force --info %s|grep '^You might resize at '|cut -d' ' -f5", biggie_filename);
		log_it("command = %s", command);
		mr_asprintf(&tmp, call_program_and_get_last_line_of_output(command));
		mr_free(command);

		log_it("res of it = %s", tmp); 
		totallength = (off_t)atoll(tmp);
		mr_free(tmp);
	} else {
		file_to_openin = biggie_filename;
		if (strchr(biggie_filename,'\'') != NULL) {
			mr_asprintf(&command, "md5sum \"%s\"", biggie_filename);
		} else {
			mr_asprintf(&command, "md5sum '%s'", biggie_filename);
		}
		if (!(fin = popen(command, "r"))) {
			log_OS_error("Unable to popen-in command");
			mr_free(command);
			return (1);
		}
		mr_free(command);
		mr_getline(&checksum_line, &n, fin);
		pclose(fin);
		totallength = length_of_file (biggie_filename);
	}
	lstat(biggie_filename, &biggiestruct.properties);
	if (strlen(biggie_filename) <= MAX_STR_LEN) {
		strcpy(biggiestruct.filename, biggie_filename);
	} else {
		fatal_error("biggie_filename too big");
	}
	pB = strchr(checksum_line, ' ');
	if (!pB) {
		pB = strchr(checksum_line, '\t');
	}
	if (pB) {
		*pB = '\0';
	}
	if (strlen(checksum_line) <= 64) {
		strcpy(biggiestruct.checksum, checksum_line);
	} else {
		fatal_error("checksum_line too big");
	}
	mr_free(checksum_line);

	mr_asprintf(&tmp, slice_fname(biggie_file_number, 0, bkpinfo->tmpdir, ""));
	fout = mr_fopen(tmp, "w");
	mr_free(tmp);

	(void) fwrite((void *) &biggiestruct, 1, sizeof(biggiestruct), fout);
	if (fout) {
		mr_fclose(fout);
	}
	length = totallength / optimal_set_size / 1024;
	mr_msg(1, "Opening in %s; slicing it and writing to CD/tape",
			file_to_openin);
	if (!(fin = fopen(file_to_openin, "r"))) {
		log_OS_error("Unable to openin biggie_filename");
		mr_asprintf(&tmp, "Cannot archive bigfile '%s': not found",
				 biggie_filename);
		log_to_screen(tmp);
		mr_free(tmp);
		return (1);
	}
	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		res =
			move_files_to_stream(slice_fname(biggie_file_number, 0,
											 bkpinfo->tmpdir, ""), NULL);
	} else {
		res =
			move_files_to_cd(slice_fname(biggie_file_number, 0,
										 bkpinfo->tmpdir, ""), NULL);
	}
	if (is_this_file_compressed(biggie_filename)
		|| bkpinfo->compression_level == 0) {
		mr_asprintf(&suffix, "");
		should_I_compress_slices = FALSE;
	} else {
		mr_asprintf(&suffix, bkpinfo->compression_suffix);
		should_I_compress_slices = TRUE;
	}
	i = bkpinfo->optimal_set_size / 256;
	for (slice_num = 1; !finished; slice_num++) {
		mr_asprintf(&curr_slice_fname_uncompressed,
			   slice_fname(biggie_file_number, slice_num, bkpinfo->tmpdir,
						   ""));
		mr_asprintf(&curr_slice_fname_compressed,
			   slice_fname(biggie_file_number, slice_num, bkpinfo->tmpdir,
						   suffix));

		mr_asprintf(&tmp, percent_media_full_comment());
		update_progress_form(tmp);
		mr_free(tmp);

		if (!(fout = fopen(curr_slice_fname_uncompressed, "w"))) {
			log_OS_error(curr_slice_fname_uncompressed);
			mr_free(curr_slice_fname_uncompressed);
			mr_free(curr_slice_fname_compressed);
			mr_free(suffix);
			return (1);
		}
		tempblock = mr_malloc(256 * 1024);
		if ((i == bkpinfo->optimal_set_size / 256)
			&& (totalread < 1.1 * totallength)) {
			for (i = 0; i < bkpinfo->optimal_set_size / 256; i++) {
				blksize = fread(tempblock, 1, 256 * 1024, fin);
				if (blksize > 0) {
					totalread = totalread + blksize;
					(void) fwrite(tempblock, 1, blksize, fout);
				} else {
					break;
				}
			}
		} else {
			i = 0;
		}
		mr_free(tempblock);
		paranoid_fclose(fout);
		if (i > 0)				// length_of_file (curr_slice_fname_uncompressed)
		{
			if (!does_file_exist(curr_slice_fname_uncompressed)) {
				mr_msg(2,
						"Warning - '%s' doesn't exist. How can I compress slice?",
						curr_slice_fname_uncompressed);
			}
			if (should_I_compress_slices && bkpinfo->compression_level > 0) {
				mr_asprintf(&command, "%s -%d %s", bkpinfo->compression_tool,
						 bkpinfo->compression_level,
						 curr_slice_fname_uncompressed);
				mr_msg(2, command);
				if ((res = system(command))) {
					log_OS_error(command);
				}
				mr_free(command);
				//          did_I_compress_slice = TRUE;
			} else {
				/* BERLIOS: Useless 
				   mr_asprintf(&command, "mv %s %s 2>> %s",
				   curr_slice_fname_uncompressed,
				   curr_slice_fname_compressed, MONDO_LOGFILE);
				 */
				res = 0;		// don't do it :)
				//          did_I_compress_slice = FALSE;
			}
			retval += res;
			if (res) {
				mr_msg(2, "Failed to compress the slice");
			}
			if ((bkpinfo->compression_type == lzo)
				&& strcmp(curr_slice_fname_compressed,
						  curr_slice_fname_uncompressed)) {
				unlink(curr_slice_fname_uncompressed);
			}
			if (res) {
				mr_asprintf(&tmp, "Problem with slice # %ld", slice_num);
			} else {
				mr_asprintf(&tmp,
						 "%s - Bigfile #%ld, slice #%ld compressed OK          ",
						 biggie_filename, biggie_file_number + 1,
						 slice_num);
			}
			if (!g_text_mode) {
				newtDrawRootText(0, g_noof_rows - 2, tmp);
				newtRefresh();
			} else {
				mr_msg(2, tmp);
			}
			mr_free(tmp);
			mr_asprintf(&file_to_archive, curr_slice_fname_compressed);
			g_current_progress++;
		} else {				/* if i==0 then ... */

			finished = TRUE;
			mr_asprintf(&file_to_archive, curr_slice_fname_uncompressed);
			if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
				break;
			}
		}

		if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
			register_in_tape_catalog(biggieslice, biggie_file_number,
									 slice_num, file_to_archive);
			maintain_collection_of_recent_archives(bkpinfo->tmpdir,
												   file_to_archive);
			res = move_files_to_stream(file_to_archive, NULL);
		} else {
			res = move_files_to_cd(file_to_archive, NULL);
		}
		mr_free(file_to_archive);
		retval += res;
		if (res) {
			mr_asprintf(&tmp,
					 "Failed to add slice %ld of bigfile %ld to scratchdir",
					 slice_num, biggie_file_number + 1);
			log_to_screen(tmp);
			mr_free(tmp);
			fatal_error
				("Hard disk full. You should have bought a bigger one.");
		}
		mr_free(curr_slice_fname_uncompressed);
		mr_free(curr_slice_fname_compressed);
	}
	mr_free(suffix);
	paranoid_fclose(fin);
	if (retval) {
		mr_asprintf(&tmp, "Sliced bigfile #%ld...FAILED",
				 biggie_file_number + 1);
	} else {
		mr_asprintf(&tmp, "Sliced bigfile #%ld...OK!",
				 biggie_file_number + 1);
	}
	mr_msg(1, tmp);
	mr_free(tmp);
	return (retval);
}


/**
 * Remove the archives in @c d.
 * This could possibly include any of:
 * - all afioballs (compressed and not)
 * - all filelists
 * - all slices
 * - all checksums
 * - a zero filler file
 *
 * @param d The directory to wipe the archives from.
 * @ingroup utilityGroup
 */
void wipe_archives(char *d)
{
	/*@ buffers ********************************************* */
	char *tmp = NULL;
	char *dir = NULL;

	assert_string_is_neither_NULL_nor_zerolength(d);

	mr_asprintf(&dir, "%s/archives", d);
	mr_asprintf(&tmp, "find %s -name '*.afio*' -exec rm -f '{}' \\;", dir);
	run_program_and_log_output(tmp, FALSE);
	mr_free(tmp);
	mr_asprintf(&tmp, "find %s -name '*list.[0-9]*' -exec rm -f '{}' \\;",
			 dir);
	run_program_and_log_output(tmp, FALSE);
	mr_free(tmp);

	mr_asprintf(&tmp, "find %s -name 'slice*' -exec rm -f '{}' \\;", dir);
	run_program_and_log_output(tmp, FALSE);
	mr_free(tmp);

	mr_asprintf(&tmp, "rm -f %s/cklist*", dir);
	run_program_and_log_output(tmp, FALSE);
	mr_free(tmp);

	mr_asprintf(&tmp, "rm -f %s/zero", dir);
	run_program_and_log_output(tmp, FALSE);
	mr_free(tmp);

	mr_msg(1, "Wiped %s's archives", dir);
	mr_asprintf(&tmp, "ls -l %s", dir);
	run_program_and_log_output(tmp, FALSE);
	mr_free(tmp);

	mr_free(dir);
}


/**
 * @addtogroup LLarchiveGroup
 * @{
 */
/**
 * Write the final ISO image.
 * @param bkpinfo The backup information structure. Used only
 * in the call to @c write_iso_and_go_on().
 * @return The number of errors encountered (0 for success)
 * @see write_iso_and_go_on
 * @see make_iso_fs
 * @bug The final ISO is written even if there are no files on it. In practice,
 * however, this occurs rarely.
 */
int write_final_iso_if_necessary()
{
	/*@ int ***************************************************** */
	int res;

	/*@ buffers ************************************************** */
	char *tmp = NULL;

	assert(bkpinfo != NULL);

// I should really check if there are any slices or tarballs to be copied to CD-R(W)'s; the odds are approx. 1 in a million that there are no files here, so I'll just go ahead & make one more CD anyway

	mr_asprintf(&tmp, "Writing the final ISO");
	mr_msg(2, tmp);
	/* BERLIOS: Doesn't work on allocated chains anymore
	center_string(tmp, 80);
	*/
#ifndef _XWIN
	if (!g_text_mode) {
		newtPushHelpLine(tmp);
	}
#endif
	mr_free(tmp);
	res = write_iso_and_go_on(TRUE);
#ifndef _XWIN
	if (!g_text_mode) {
		newtPopHelpLine();
	}
#endif
	mr_msg(2, "Returning from writing final ISO (res=%d)", res);
	return (res);
}


/**
 * Write an ISO image to <tt>[bkpinfo->isodir]/bkpinfo->prefix-[g_current_media_number].iso</tt>.
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_media_type
 * - @c prefix
 * - @c isodir
 * - @c manual_tray
 * - @c media_size
 * - @c nfs_mount
 * - @c nfs_remote_dir
 * - @c scratchdir
 * - @c verify_data
 *
 * @param last_cd If TRUE, this is the last CD to write; if FALSE, it's not.
 * @return The number of errors encountered (0 for success)
 * @see make_iso_fs
 */
int write_iso_and_go_on(bool last_cd)
{
	/*@ pointers **************************************************** */
	FILE *fout;

	/*@ buffers ***************************************************** */
	char *tmp;
	char *cdno_fname;
	char *lastcd_fname;
	char *isofile;

	/*@ bool ******************************************************** */
	bool that_one_was_ok;
	bool orig_vfy_flag_val;

	/*@ int *********************************************************** */
	int res = 0;

	assert(bkpinfo != NULL);
	orig_vfy_flag_val = bkpinfo->verify_data;
	if (bkpinfo->media_size <= 0L) {
		fatal_error("write_iso_and_go_on() - unknown media size");
	}

	mr_msg(1, "OK, time to make %s #%d",
			bkpinfo->backup_media_string,
			g_current_media_number);

	/* label the ISO with its number */

	mr_asprintf(&cdno_fname, "%s/archives/THIS-CD-NUMBER",
			 bkpinfo->scratchdir);
	fout = fopen(cdno_fname, "w");
	fprintf(fout, "%d", g_current_media_number);
	paranoid_fclose(fout);
	mr_free(cdno_fname);

	mr_asprintf(&tmp, "cp -f %s/autorun %s/", MONDO_SHARE,
			 bkpinfo->scratchdir);
	if (run_program_and_log_output(tmp, FALSE)) {
		mr_msg(2, "Warning - unable to copy autorun to scratchdir");
	}
	mr_free(tmp);

	/* last CD or not? Label accordingly */
	mr_asprintf(&lastcd_fname, "%s/archives/NOT-THE-LAST",
			 bkpinfo->scratchdir);
	if (last_cd) {
		unlink(lastcd_fname);
		mr_msg(2,
				"OK, you're telling me this is the last CD. Fair enough.");
	} else {
		fout = fopen(lastcd_fname, "w");
		fprintf(fout,
				"You're listening to 90.3 WPLN, Nashville Public Radio.\n");
		paranoid_fclose(fout);
	}
	mr_free(lastcd_fname);

	if (space_occupied_by_cd(bkpinfo->scratchdir) / 1024 > bkpinfo->media_size) {
		mr_asprintf(&tmp,
				"Warning! %s is too big. It occupies %ld KB, which is more than the %ld KB allowed.",
				media_descriptor_string(bkpinfo->backup_media_type),
				(long) space_occupied_by_cd(bkpinfo->scratchdir),
				bkpinfo->media_size);
		log_to_screen(tmp);
		mr_free(tmp);
	}
	if (bkpinfo->backup_media_type != usb) {
		mr_asprintf(&isofile, "%s/%s/%s-%d.iso", bkpinfo->isodir,
			bkpinfo->nfs_remote_dir, bkpinfo->prefix,
			g_current_media_number);
	} else {
	}
	for (that_one_was_ok = FALSE; !that_one_was_ok;) {
		if (bkpinfo->backup_media_type != usb) {
			res = make_iso_fs(isofile);
		} else {
			res = make_usb_fs();
		}
		if (g_current_media_number == 1 && !res
			&& (bkpinfo->backup_media_type == cdr
				|| bkpinfo->backup_media_type == cdrw)) {
			if (find_cdrom_device(tmp, FALSE))	// make sure find_cdrom_device() finds, records CD-R's loc
			{
				mr_msg(3, "*Sigh* Mike, I hate your computer.");
				bkpinfo->manual_tray = TRUE;
			}					// if it can't be found then force pausing
			else {
				mr_msg(3, "Great. Found Mike's CD-ROM drive.");
			}
		}
		if (bkpinfo->verify_data && !res) {
			log_to_screen
				("Please reboot from the 1st %s in Compare Mode, as a precaution.",
				 media_descriptor_string(g_backup_media_type));
			chdir("/");
			iamhere("Before calling verification of image()");
			if (bkpinfo->backup_media_type == usb) {
				res += verify_usb_image();
			} else {
				res += verify_cd_image();
			}
			iamhere("After calling verification of image()");
		}
		if (!res) {
			that_one_was_ok = TRUE;
		} else {
			mr_asprintf(&tmp, "Failed to burn %s #%d. Retry?",
					 bkpinfo->backup_media_string,
					 g_current_media_number);
			res = ask_me_yes_or_no(tmp);
			mr_free(tmp);
			if (!res) {
				if (ask_me_yes_or_no("Abort the backup?")) {
					fatal_error("FAILED TO BACKUP");
				} else {
					break;
				}
			} else {
				mr_msg(2, "Retrying, at user's request...");
				res = 0;
			}
		}
	}
	mr_free(isofile);

	g_current_media_number++;
	wipe_archives(bkpinfo->scratchdir);
	mr_asprintf(&tmp, "rm -Rf %s/images/*gz %s/images/*data*img",
			 bkpinfo->scratchdir, bkpinfo->scratchdir);
	if (system(tmp)) {
		mr_msg(2,
				"Error occurred when I tried to delete the redundant IMGs and GZs");
	}
	mr_free(tmp);

	if (last_cd) {
		mr_msg(2, "This was your last media.");
	} else {
		mr_msg(2, "Continuing to backup your data...");
	}

	bkpinfo->verify_data = orig_vfy_flag_val;
	return (0);
}

/* @} - end of LLarchiveGroup */


/**
 * Verify the user's data.
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_data
 * - @c backup_media_type
 * - @c media_device
 * - @c verify_data
 *
 * @return The number of errors encountered (0 for success)
 * @ingroup verifyGroup
 */
int verify_data()
{
	int res = 0, retval = 0, cdno = 0;
	char *tmp = NULL;
	long diffs = 0;

	assert(bkpinfo != NULL);
	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		chdir("/");
		mvaddstr_and_log_it(g_currentY, 0,
							"Verifying archives against live filesystem");
		verify_tape_backups();
		mvaddstr_and_log_it(g_currentY++, 74, "Done.");
	} else if (bkpinfo->backup_data)
		//bkpinfo->backup_media_type == cdrw || bkpinfo->backup_media_type == cdr))
	{
		mr_msg(2,
				"Not verifying again. Per-CD/ISO verification already carried out.");
		sprintf(tmp, "cat %s/changed.files > %s/changed.files 2> /dev/null",bkpinfo->tmpdir, MONDO_CACHE);
		paranoid_system(tmp);
	} else {
		g_current_media_number = cdno;
		chdir("/");
		for (cdno = 1; cdno < 99 && bkpinfo->verify_data; cdno++) {
			if (cdno != g_current_media_number) {
				mr_msg(2,
						"Warning - had to change g_current_media_number from %d to %d",
						g_current_media_number, cdno);
				g_current_media_number = cdno;
			}
			if (bkpinfo->backup_media_type != iso) {
				insist_on_this_cd_number(cdno);
			}
			res = verify_cd_image();	// sets verify_data to FALSE if it's time to stop verifying
			retval += res;
			if (res) {
				mr_asprintf(&tmp,
						"Warnings/errors were reported while checking %s #%d",
						media_descriptor_string(bkpinfo->backup_media_type),
						g_current_media_number);
				log_to_screen(tmp);
				mr_free(tmp);

			}
		}
		mr_asprintf(&tmp,
				"grep 'afio: ' %s | sed 's/afio: //' | grep -vE '^/dev/.*$' >> %s/changed.files",
				MONDO_LOGFILE, MONDO_CACHE);
		system(tmp);
		mr_free(tmp);

		mr_asprintf(&tmp,
				"grep 'star: ' %s | sed 's/star: //' | grep -vE '^/dev/.*$' >> %s/changed.files",
				MONDO_LOGFILE, MONDO_CACHE);
		system(tmp);
		mr_free(tmp);

		run_program_and_log_output("umount " MNT_CDROM, FALSE);
		eject_device(bkpinfo->media_device);
	}
	sprintf(tmp, "%s/changed.files", MONDO_CACHE);
	diffs = count_lines_in_file(tmp);

	if (diffs > 0) {
		if (retval == 0) {
			retval = (int) (-diffs);
		}
	}
	return (retval);
}


void setenv_mondo_var(void) {

	char *tmp = NULL;
	char *p = NULL;
	char *path_min = "/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin";

	mr_setenv("MONDO_SHARE",MONDO_SHARE);
	mr_setenv("MONDORESTORECFG",MONDORESTORECFG);
	mr_setenv("MONDO_CACHE",MONDO_CACHE);
	/* Add the ARCH environment variable for ia64 purposes */
	mr_setenv("ARCH", get_architecture());


	if ((p = getenv("PATH")) == NULL) {
		mr_asprintf(&tmp, path_min);
	} else {
		mr_asprintf(&tmp, "%s:%s",p, path_min);
	}
	mr_setenv("PATH",tmp);
	mr_free(tmp);
}
