#!/bin/sh
#
#	$Header: /home/kbackup/CVSROOT/KBackup/kbackup,v 1.53 1997/09/19 19:49:15 kbackup Exp $
# This file is Copyright (C) 1995-1997 by Karsten Ballder (Ballueder@usa.net)
#
# It is part of the KBackup package, see the file COPYING for details.
# KBackup and all files included in this package are licensed and protected
# under the terms and conditions of the GNU General Public License Version 2.
#
#	If you want to contact the current maintainer of this software, please
#	send e-mail to: KBackup@usa.net
#

#
#	set default values for Variables
#

VERSION="1.2.11"
NUMVERSION=10211

echo "Initialising, phase 1..."

SED=sed
FGREP=fgrep
GREP=grep
TAR=tar
AFIO=afio
DD=dd
DIALOG=dialog
MAIL=mail
WC=/usr/bin/wc
MULTIBUF=multibuf
STD_COMPRESS=gzip		# for logfiles, if no compression set

AFIO_PROGRAMS="gzip sh afio"	# to rescue them from being overwritten,
				# nasty bug in afio 2.4.1

PATHFILE=paths
CHECKPRGS=checkprogs
if [ "$SRCDIR" = "" ]
then
	SRCDIR=/usr/KBackup
fi

RESTORE_SRC=restore_src
Restore_src_loaded=NO
BACKUP_SRC=backup_src
Backup_src_loaded=NO
READDATA_SRC=read_data_src
ReadData_src_loaded=NO
VERIFY_SRC=verify_src
Verify_src_loaded=NO
WriteData_src_loaded=NO
WRITEDATA_SRC=write_data_src
Blockdev_src_loaded=NO
BLOCKDEV_SRC=blockdev_src
AUTODETECT_SRC=autodetect_src
Autodetect_src_loaded=NO
DIALOG_SRC=dialog

Configuration_changed=NO

SOURCE_FILES="$RESTORE_SRC $BACKUP_SRC $BLOCKDEV_SRC $VERIFY_SRC $AUTODETECT_SRC $READDATA_SRC $WRITEDATA_SRC subroutines checkprogs paths"

DIALOGTITLE="KBackup Version $VERSION             Copyright (C) 1995-1997 by Karsten Ballder"
MAILADDRESS="KBackup@usa.net"

FILESPERARCHIVE_STD=3
FILESPERARCHIVE="$FILESPERARCHIVE_STD"
			# compression method, cont-dir, archive
			#   +1 for every multibuf end marker when using
			# sequence information ==> 5

BLOCKDEV_HEADER="KBackup-Header"
BLOCKDEV_DIRECTORY="Directory"
BLOCKDEV_ARCHIVE="Archive"

KBACKDIRDEFAULT=.KBackup
KBACKRCDEFAULT=.kbackrc

STD_TAROPT_BACK="--sparse "
STD_TAROPT_REST="--sparse "
STD_AFIOOPT_BACK=""
STD_AFIOOPT_REST=""
STD_MULTIBUF_OPT=""
MBUF_TAPE_CMD1="mt -f \"\$device\" rewind && dialog --title 'KBackup: MultiBuf' --msgbox '\nPlease insert next volume...' 7 34 && clear"
MBUF_TAPE_CMD2="mt -f \"\$device\" rewind"
MBUF_TAPE_CMD1_TTY="mt -f \"\$device\" rewind && echo -ne '\nPlease insert next volume and press ENTER...'  && read "
MBUF_TAPE_CMD2_TTY="mt -f \"\$device\" rewind"

# MultiBuf Commands for BLOCKDEV: command1, command2, retry-command:

MBUF_BLOCKDEV_WCMD1="umount \$MOUNTPOINT && dialog --title 'KBackup: MultiBuf' --msgbox '\nPlease insert next volume...' 7 34 && clear"
MBUF_BLOCKDEV_WCMD2="mount -t \$blockdev_fs_type \"\$device\" \$MOUNTPOINT"
MBUF_BLOCKDEV_RCMD1="umount \$MOUNTPOINT && dialog --title 'KBackup: MultiBuf' --msgbox '\nPlease insert next volume...' 7 34 && clear"
MBUF_BLOCKDEV_RCMD2="mount -t \$blockdev_fs_type \"\$device\" \$MOUNTPOINT"
MBUF_BLOCKDEV_RCMDR="umount \$MOUNTPOINT && dialog --title 'KBackup: MultiBuf' --yesno '\nDetected wrong sequence number!\nRetry with another volume?' 7 38 && mount -t \$blockdev_fs_type \"\$device\" \$MOUNTPOINT"

export blockdev_fs_type device MOUNTPOINT

# Multibuf Commands for ttymode:

MBUF_BLOCKDEV_WCMD1_TTY="umount \$MOUNTPOINT && echo -ne '\nPlease insert next volume and press ENTER...' && read "
MBUF_BLOCKDEV_WCMD2_TTY="mount -t \$blockdev_fs_type \"\$device\" \$MOUNTPOINT"
MBUF_BLOCKDEV_RCMD1_TTY="umount \$MOUNTPOINT && echo -ne '\nPlease insert next volume and press ENTER...'  && read "
MBUF_BLOCKDEV_RCMD2_TTY="mount -t \$blockdev_fs_type \"\$device\" \$MOUNTPOINT"
MBUF_BLOCKDEV_RCMDR_TTY="umount \$MOUNTPOINT && echo -ne '\n\aERROR: Detected wrong sequence number!\nEnter Y to retry with another volume. '  && read tmp
&& test "$tmp" = "Y" -o "$tmp" = "y"  && mount -t \$blockdev_fs_type \"\$device\" \$MOUNTPOINT"



FIND_STD_OPTS="-noleaf -depth"	# to avoid endless errors on non unix fs
				# -depth to avoid errors with unreadable dirs
				# see cpio(1) man page for details

kbackdir="$HOME/$KBACKDIRDEFAULT"
MOUNTPOINT="$kbackdir/mnt"
parent=/
local=NO
incremental=NO
specifiedfilesonly=NO
datestamp=`date +"%D %T"`
directoriesonly=YES
findxpertmode=NO
findxpertflags=-print
compression=GZIP		#valid: GZIP, PGP, NONE, COMPRESS
compress_options=-1
decompress_options=-d
archive_format=AFIO		#valid: TAR 
verify_archive=YES
pgpkey=root
configname=Default
ddbufsize=10
double_buffering=YES
device=/dev/tape
resetdevice=/dev/tape-reset
device_type=TAPE		# valid: TAPE, FLOPPY, BLOCKDEV, FILE
arch_filename="KBackup-Arc"
blockdev_fs_type=ext2
blockdev_mkfs="mkfs -t ext2 -c"
floppy_format="1722/1440"
manualedit=NO
followtarops=YES
scheduled=NO
schedulename=scheduled
scheduletime="???"
oldconfigname="$configname"
use_multibuf=YES
multibuf_nblocks=100
multibuf_blksize=1024
multibuf_seq_info=YES
multibuf_cmd1=DEFAULT
multibuf_cmd2=DEFAULT
restore_write_log=YES
CreateReport=NO
ReportCommand="lpr"
AutoRewind=YES
protect_newer=YES
use_patterns=NO
manual_command="dialog --textbox /usr/doc/KBackup/manual.asc 24 77"
afio_user_opts="-T 3k"
tar_user_opts=
syncto=10240
waittime=5

TMP=/tmp
realTMP=$TMP
TMP=$TMP/kbtmp$$

DATEFILE=kbdate$$
TMPFILE=kbtmp$$
TMPFILE2=kbtmpB$$
BINDIR=kbfakegzip$$
COMPRESSFILE=kbcompress$$
DIALOGFILE=kbdialog$$
DIRLISTFILE=kbdirlist$$
TARLOGFILE=kbtarlog$$
TARLISTFILE=kbtarlist$$
MAILFILE=kbmail$$
EXCLUDE=kbexclude$$
PIPEFILE=kbpipe$$
MSGFILE=kbinfo$$
ERRFILE=kbstderr$$
FINDFILE=kbfind$$
STDERR="$TMP/$ERRFILE"
MBUF_SCRIPT1=kbmbcmd1$$
MBUF_SCRIPT2=kbmbcmd2$$
MBUF_SCRIPTR=kbmbcmdr$$
MVOLFLAG=kbmvolflag$$
REPORTFILE=kbreport$$
PHRASEFILE=.kbphr$$

TMPFILES="$TMP/$TMPFILE $TMP/$DIRLISTFILE $TMP/$DIALOGFILE \
	$TMP/$TARLOGFILE $TMP/$TARLISTFILE $TMP/$MSGFILE $TMP/$PIPEFILE\
	$TMP/$COMPRESSFILE $TMP/$TMPFILE2 $TMP/$BINDIR $TMP/$EXCLUDE $TMP/$ERRFILE\
	$TMP/$MBUF_SCRIPT1 $TMP/$MBUF_SCRIPT2 $TMP/$MBUF_SCRIPTR $TMP/$FINDFILE\
	$TMP/$REPORTFILE $TMP/$MAILFILE $TMP/$MVOLFLAG $TMP/$PHRASEFILE $TMP/$DATEFILE"

# set new temporary directory
changeTMP()
{
	if [ "$TMP" != "$realTMP" ] ; then
		rm -rf $TMP
		rmdir $TMP 2>/dev/null
	fi
	
	realTMP="$1"
	TMP="$1/kbtmp$$"

	STDERR="$TMP/$ERRFILE"
	TMPFILES="$TMP/$TMPFILE $TMP/$DIRLISTFILE $TMP/$DIALOGFILE \
	$TMP/$TARLOGFILE $TMP/$TARLISTFILE $TMP/$MSGFILE $TMP/$PIPEFILE\
	$TMP/$COMPRESSFILE $TMP/$TMPFILE2 $TMP/$BINDIR $TMP/$EXCLUDE $TMP/$ERRFILE\
	$TMP/$MBUF_SCRIPT1 $TMP/$MBUF_SCRIPT2 $TMP/$MBUF_SCRIPTR $TMP/$FINDFILE\
	$TMP/$REPORTFILE $TMP/$MAILFILE $TMP/$MVOLFLAG $TMP/$PHRASEFILE"
}


check_for_source_files()
{
	echo -e "\tchecking for required source files in $SRCDIR..."
	for i in $SOURCE_FILES
	do
		test -r "$SRCDIR/$i"
		if [ $? != 0 ]
		then
			echo -e "\t\aFATAL ERROR:"$i" not found!"
			exit 1
		else
			echo -en " $i"
		fi
	done
	echo 
}

Init()
{
	check_for_source_files
	
	echo "Initialising, phase 2..."

	if [ ! -d $TMP ] ; then
		mkdir $TMP
		if [ $? != 0 ] ; then
			echo -e "\t\aCannot make $TMP!"
			exit 1
		fi
	fi
	


	if [ "$scheduled" != "YES" ] 
	then
		if [ -r "$HOME/$KBACKRCDEFAULT" ] ; then
			echo -e "\tReading $HOME/$KBACKRCDEFAULT..."
			. "$HOME/$KBACKRCDEFAULT"
		fi
	fi
	
	if [ -r "$SRCDIR/$PATHFILE" ] ; then
		echo -e "\tReading $SRCDIR/$PATHFILE..."
		. "$SRCDIR/$PATHFILE"
		. "$SRCDIR/$CHECKPRGS"
		DIALOG_SRC_FILE=""
		check_progs
		report_missing -noprompt
		if [ $HasDIALOG = NO -o "$TTYMODE" = YES ]
		then
			echo -e "\tLoading dialog-emulation script..."
			. "$SRCDIR/$DIALOG_SRC"
		fi
		MYDIALOGTITLE="$DIALOGTITLE"
		. "$SRCDIR/subroutines"
		check_error
	fi

	if [ ! -d "$kbackdir" ] ; then
		echo -e "\tCreating $kbackdir..."
		mkdir "$kbackdir"
		check_error
	fi

	MOUNTPOINT="$kbackdir/mnt"
	if [ ! -d "$MOUNTPOINT" ] ; then
		echo -e "\tCreating $MOUNTPOINT..."
		mkdir "$MOUNTPOINT"
		check_error
	fi
	
	if [ ! -d "$datadir" ] ; then
		echo -e "\tCreating $datadir..."
		mkdir "$datadir"
		check_error
	fi
	
	if [ ! -d "$datadir/$configname" ] ; then
		echo -e "\tCreating $datadir/$configname..."
		mkdir "$datadir/$configname"
		check_error
	fi

	if [ -r "$datadir/$configname/Config" ] ; then
		echo -e "\tReading $datadir/$configname/Config..."
		. "$datadir/$configname/Config"
		check_error
		changeTMP "$TMP"
	fi

	if [ -r "$datadir/$configname/DateStamp" -a -s $kbackdir/$configname/DateStamp ]
	then 
		datestamp=`cat $datadir/$configname/DateStamp` 2>$STDERR
		check_error
	fi

	touch "$datadir/$configname/Include_Files" 2>/dev/null
	touch "$datadir/$configname/Exclude_Files" 2>/dev/null
	touch "$datadir/$configname/Include_Patterns" 2>/dev/null
	touch "$datadir/$configname/Exclude_Patterns" 2>/dev/null

	if [ ! -d "$MOUNTPOINT" ] ; then
		echo -e "\tCreating mountpoint $MOUNTPOINT..."
		mkdir "$MOUNTPOINT"
		check_error
	fi
	rm -f $MOUNTPOINT/* 2>/dev/null
	
	if [ "$EDITOR" = "" ] ; then
		EDITOR=vi
	fi
	save_options	# to initialise old_* variables
}

Calculate_MaxArcLen()
{
	# round to kilobytes and add 100Kb for safety:
	set -f
	bytes_written=`expr \( \( $bytes_written / 1024 \) + 100 \) * 1024`
	set +f

	maxarchivelength=`expr $tapelength - $bytes_written`
}


Backup()
{
	if [ "$Backup_src_loaded" != "YES" ]
	then
		. "$SRCDIR/$BACKUP_SRC"
	fi
	Backup_II
}


Get_BackupSize()
{
	InfoBox "Creating list of files..."
	
	build_find_arguments

	echo >$TMP/$TMPFILE2
	cd "$parent"
	set -f
	echo find . "$findargs" -fprintf $TMP/$TMPFILE2 \"%k\\n\" >$TMP/$FINDFILE
	. "$TMP/$FINDFILE" 2>/dev/null
	set +f

	InfoBox "Adding file sizes..."

	size=`$AWK '{ count = count + $1 ; }
	END { print count ; }' <$TMP/$TMPFILE2 `
	
	MsgBox \
"Total backup size before compression
is $size KiloBytes ( = `expr \( $size + 512 \) / 1024` MB).

If using compression you will need
roughly half that space on your 
backup media."
}


View_Logfile()
{
	cd $datadir
	find * -type d -prune -printf "%f %Tx\n" | sort >$TMP/$TMPFILE

	$DIALOG   --menu "Choose a configuration:" 20 60 `$WC -l <$TMP/$TMPFILE` \
		`cat $TMP/$TMPFILE` 2>$TMP/$DIALOGFILE
	if [ $? = 0 ]
	then
		dir=`cat $TMP/$DIALOGFILE`
		find "$datadir/$dir" -type f -prune -printf "%f %Tx\n" |\
		$FGREP "Log" | sort >$TMP/$TMPFILE
		$DIALOG   --menu "Choose a logfile:" 20 60 `$WC -l <$TMP/$TMPFILE` \
			`cat $TMP/$TMPFILE` 2>$TMP/$DIALOGFILE
		if [ $? = 0 ]
		then
			old_compression="$compression"
			touch $TMP/$PHRASEFILE
			uncompress_logfile "$datadir/$dir/`cat $TMP/$DIALOGFILE`" 3<$TMP/$PHRASEFILE
			$DIALOG   --title "`cat $TMP/$DIALOGFILE`" --textbox $TMP/$TMPFILE 23 75 2>/dev/null
			
			compression="$old_compression"
		fi
	fi
}


Delete_Logfile()
{
	cd "$datadir"
	find * -type d -prune -printf "%f %Tx\n" | sort >$TMP/$TMPFILE
	$DIALOG   --menu "Choose a configuration:" 20 60 `$WC -l <$TMP/$TMPFILE` \
		`cat $TMP/$TMPFILE` 2>$TMP/$DIALOGFILE
	if [ $? = 0 ]
	then
		dir=`cat $TMP/$DIALOGFILE`
		cd "$dir"
		find * -type f -prune -printf "%f %Tx\n" |\
		$FGREP "Log" | sort >$TMP/$TMPFILE
		$DIALOG   --menu "Choose a logfile:" 20 60 `$WC -l <$TMP/$TMPFILE` \
			`cat $TMP/$TMPFILE` 2>$TMP/$DIALOGFILE
		if [ $? = 0 ]
		then
			filename=`cat $TMP/$DIALOGFILE`
			if [ -f "$filename" ]
			then
				$DIALOG --title " Please confirm: " --yesno \
				"\nDelete "$datadir/$dir/$filename" ?" 7 60
				if [ $? = 0 ]
				then
					rm "$filename"
				fi
			fi
		else
			MsgBox "No logfiles found."
		fi
	fi
}

View_Contents()
{	
	backup_version="???"
	backup_date="???"
	backup_compression="???"
	backup_type="???"
	backup_files_per_archive="???"
	backup_archive_format="???"
	backup_donly="???"
	backup_use_multibuf="???"
	backup_multibuf_blksize="???"
	backup_multibuf_nblocks="???"
	backup_multibuf_seq_info="???"
	backup_parent="???"

	if [ "$ReadData_src_loaded" != "YES" ]
	then
		. "$SRCDIR/$READDATA_SRC" 2>$STDERR || ( check_error ; return )
	fi
	if [ "$Blockdev_src_loaded" != "YES" ]
	then
		. "$SRCDIR/$BLOCKDEV_SRC" 2>$STDERR || ( check_error ; return )
	fi
	
	insert_media
	if [ $? != 0 ]
	then
		return
	fi

	auto_rewind

	if [ "$device_type" != "FLOPPY" ]
	then
			if [ "$device_type" = "BLOCKDEV" ]
			then
				dirfile="$MOUNTPOINT/$arch_filename.dir"
				header="$MOUNTPOINT/$arch_filename.hdr"
				archive="$MOUNTPOINT/$arch_filename.arc"
				get_blockdev READ
			else	if [ "$device_type" = "FILE" ]
				then
					dirfile="$arch_filename.dir"
					header="$arch_filename.hdr"
					archive="$arch_filename.arc"
				else
					dirfile="$device"
					header="$device"
					archive="$device"
				fi
			fi
			
			InfoBox "Reading header..." 
			read_data -raw "$header" >$TMP/$TMPFILE 2>$STDERR
			check_error -dev
			if [ $? != 0 ]
			then
				release_blockdev
				return
			else
				if read firstline < $TMP/$TMPFILE && [ "$firstline" = "#KBackup" ]
				then
					. $TMP/$TMPFILE && $DIALOG   --title "Archive header information" --msgbox "\n\
Archive created by KBackup Version: $backup_version\n\
  files per archive: .............. $backup_filesperarchive\n\
Creation date: .................... $backup_date\n\
Backup type: ...................... $backup_type\n\
Archive format: ................... $backup_archive_format\n\
Compression method: ............... $backup_compression\n\
Directories-only flag: ............ $backup_donly\n\
  using Multibuf: ................. $backup_use_multibuf\n\
  Multibuf blocksize: ............. $backup_multibuf_blksize\n\
  Multibuf number of blocks: ...... $backup_multibuf_nblocks\n\
\n\
Parent Directory of Backup: ....... $backup_parent\n" 20 75 
        
				else
					ErrorBox "File is not a valid KBackup Archive Header."
					release_blockdev
					return
				fi
			fi
		#fi
		if [ "$compression" = "PGP" ]
		then
			GetPGPPASS
		fi
		set_compress
	
		InfoBox "Reading directory..." 
		touch $TMP/$PHRASEFILE
		( read_data "$dirfile" | $uncompress ) >$TMP/$TMPFILE 2>$STDERR 3<$TMP/$PHRASEFILE
		if check_compress_success
		then
			$DIALOG   --title "Archive contents directory" --textbox $TMP/$TMPFILE 23 75
		else
			beep
			ErrorBox "Cannot read contents directory.
Maybe tape at wrong position?" 8 40
		fi	
	else		# device is floppy
		if [ "$archive_format" = "TAR" ]
		then
			$TAR -tvf "$device" 2>&1 >$TMP/$TMPFILE
		else
			blocks=`echo $floppy_format|$SED '1,$ s/\(.*\)\/.*/\1k/g' `
			$AFIO -tlvF -s $blocks "$device" 2>&1 >$TMP/$TMPFILE
		fi
		if [ $? -eq 0 ]
		then
			$DIALOG   --title "Archive contents directory" --textbox $TMP/$TMPFILE 23 75
		else
			ErrorBox "Reading of archive contents failed!"
		fi
	fi
	release_blockdev
	clear_PGP
}	


Restore()
{
	if [ "$Restore_src_loaded" != "YES" ]
	then
		. "$SRCDIR/$RESTORE_SRC"
	fi
	Restore_II
}

schedule()
{
	schedulename=scheduledd
	oldconfigname="$configname"
	configname="$schedulename"
	save_config
	configname="$oldconfigname"
	echo oldconfigname="\"$configname\"" >>$datadir/$schedulename/Config
	echo scheduled=YES >>"$datadir/$schedulename/Config"
}

unschedule()
{
	configname="$oldconfigname"
	save_configname
}

enter_time()
{
	$DIALOG   --inputbox "Please enter time and date in at(1) format:\n\
Current time and date is: `date`." 9 75 2>$TMP/$DIALOGFILE 
	if [ $? = 0 ] && test -n "`cat $TMP/$DIALOGFILE`"
	then
		scheduletime=`cat $TMP/$DIALOGFILE`
	fi
}

do_schedule()
{
	while : ; do
	$DIALOG   --title "Scheduling" --menu "Please choose:" 12 38 5 \
		T	"Set date and time" \
		B	"Schedule a backup" \
		R	"Schedule a restore" \
		M	"Back to main menu" 2>$TMP/$DIALOGFILE
	if [ $? = 0 ]
	then
		case `cat $TMP/$DIALOGFILE` in
			T)	enter_time
				Configuration_changed=YES
				;;
			B)	schedule
				echo "$0 --scheduled-backup $schedulename" | at $scheduletime 
				exit
				;;
			R)	Restore_part_I
				if [ "$restore_part_I" = "FAILED" ]
				then
					return
				fi
				schedule
				pwd
				read
				echo "$0 --scheduled-restore $schedulename" | at $scheduletime 
				exit
				;;
			M)	schedule=NO
				return
				;;
		esac
	else
		schedule=NO
		return
	fi
	done
}

Verify()	# accepts option "auto" to avoid prompt for medium
{
	if [ "$Verify_src_loaded" != "YES" ]
	then
		. "$SRCDIR/$VERIFY_SRC"
	fi
	Verify_II $1
}

cleanup()
{
	rm -rf $TMP 2>/dev/null
}

set_multivolume()
{
	multivolume=YES

	if [ "$archive_format" = "TAR" ]
	then
		if [ "$protect_newer" = "YES" ]
		then
			protect_newer=NO
			Configuration_changed=YES
			MsgBox \
"You have selected TAR archive format
and chosen to protect newer files during
restore. This is not possible with tar.

Disabling protection feature."
		fi

		if [ "$compression" != "NONE" ]
		then
			compression=NONE
			Configuration_changed=YES
			MsgBox "Switching off compression for multi-\nvolume tar-archives."
		fi
		if [ "$double_buffering" = "YES" ]
		then
			double_buffering=NO
			Configuration_changed=YES
			MsgBox "Switching off double buffering\nfor multivolume tar-archives."
		fi
	fi
}

#
#	check wether combination of options is valid:
#
Check_Settings()
{
	if [ "$archive_format" = "TAR" ]
	then
		if [ "$multivolume" = "YES" ]
		then
			if [ "$compression" != "NONE" ]
			then
				ErrorBox \
"If you want to use compressed multivolume archives,
you must use the AFIO-format, TAR is not capable of
this. Otherwise, you cannot compress or just write
archives of at most one volume's length.
Setting archive format to AFIO."
				archive_format=AFIO
				Configuration_changed=YES
			fi
			if [ "$double_buffering" = "YES" ]
			then
				ErrorBox \
"You cannot use double buffering with multivolume
archives in TAR-format. 
As TAR does not support compression with multi-
volume archives, this should not be necessary
anyway.
Switching off double buffering."
				double_buffering=NO
				Configuration_changed=YES
			fi
		fi
	fi


	if [ "$double_buffering" = "YES" ]
	then
		if [ -z "$ddbufsize" ]
		then
			ErrorBox \
"You must specify a buffersize when using double
buffering.
Setting it to 10."
			ddbufsize=10
			Configuration_changed=YES
		fi
		if [ "$device_type" = "FLOPPY" ]
		then
			ErrorBox \
"You selected double buffering for a floppy
drive. This is not possible.
Disabling double buffering."
		double_buffering=NO
		Configuration_changed=YES
		fi
	fi
	if [ "$use_patterns" = "YES" -a "$directoriesonly" = "YES" ]
	then
		ErrorBox \
"You are trying to use include/exclude shell
patterns together with the \"Directories-Only\"
setting. This is not possible, sorry.

Disabling \"Directories-Only\" setting."
		directoriesonly=NO
		Configuration_changed=YES
	fi
	if [ "$archive_format" = "AFIO"  -a "$directoriesonly" = "YES" ]
	then
		ErrorBox \
"AFIO format archives cannot use the
Directories-Only-Flag. 

It is switched off now."
		directoriesonly=NO
		Configuration_changed=YES
	fi
	if [ "$verify_archive" = "YES" ] && \
	[ "$device_type" = "BLOCKDEV" -o "$device_type" = "FILE" ]
	then
		ErrorBox \
"Verify for BLOCKDEV and FILE archives 
is not implemented.

Switching off Verify-Setting."
		verify_archive=NO
		Configuration_changed=YES
	fi
	if [ "$archive_format" = "AFIO" -a "$compression" = "PGP" -a "$HasAFIO242" != "YES" ]
	then
		MsgBox \
"You are using pgp-encryption with
an \"old\" afio program. This is 
not safe! See the manual or upgrade
to an afio version newer than 2.4.2!
"
	fi
	if [ -z "$syncto" -o $syncto -lt 2048 ]
	then
		MsgBox \
"You specified a blocksize of less
than 2048 bytes. 

Blocksize has been set to 2048.
"
		syncto=2048
		Configuration_changed=YES
	fi
}	

############################### MENU ROUTINES ##################

Compression_Menu()
{
	while :
	do
		$DIALOG   --title " Compression menu " --menu "\n\
Please choose one of the following compression methods. Before using\n\
pgp(1) for public key encryption, you should know what you are doing!\n\n\
The current compression is $compression, Options: $compress_options\n" 19 75 7 \
		N	"No compression" \
		G	"Compress using Gzip" \
		C	"Compress using Compress" \
		P	"Compress + Encrypt using Pgp" \
		O	"Set Command-line Options for compression program" \
		D	"Set Command-line Options for decompressing" \
		"<"	"Return to Backup Parameters Menu" 2>$TMP/$DIALOGFILE
	if [ $? = 0 ]
	then
		case `cat $TMP/$DIALOGFILE` in
		N)	compression=NONE
			Configuration_changed=YES
			;;
		G)	compression=GZIP
			Configuration_changed=YES
			;;
		C)	compression=COMPRESS
			Configuration_changed=YES
			;;
		P)	compression=PGP
			$DIALOG   --inputbox "Please enter name of pgp key:" 8 75 2>$TMP/$DIALOGFILE 
			if [ $? = 0 ] && test -n "`cat $TMP/$DIALOGFILE`"
			then
				pgpkey=`cat $TMP/$DIALOGFILE`
				Configuration_changed=YES
			fi
			;;
		O)	$DIALOG   --inputbox "Please enter any optional command line arguments\n\
for the compression program (e.g. -1 for gzip).\n\
Default is: \"$compress_options\"\n(Enter a single space for no options.)" 13 75 2>$TMP/$DIALOGFILE
			if [ $? = 0 ]
			then
				if [ "`cat $TMP/$DIALOGFILE`" != "" ] ; then
					compress_options=`cat $TMP/$DIALOGFILE`
					Configuration_changed=YES
				fi
			fi
			;;
		D)	$DIALOG   --inputbox "Please enter any optional command line arguments\n\
for the compression program when used for decompressing.\n\
Default is: \"$decompress_options\"\n(Enter a single space for no options.)" 13 75 2>$TMP/$DIALOGFILE
			if [ $? = 0 ]
			then
				if [ "`cat $TMP/$DIALOGFILE`" != "" ] ; then
					decompress_options=`cat $TMP/$DIALOGFILE`
					Configuration_changed=YES
				fi
			fi
			;;

		"<")	return
			;;
		esac
	else
		return
	fi
	done
}

Floppy_Format_Menu()
{
	while : ; do
		$DIALOG --title " Floppy Format Menu " --menu "\n\
Please choose a disk format to use:\n(current: $floppy_format)\n" 18 70 7\
		"1722/1440"	"1.7Mb  on a 3.5  drive" \
		"1440/1440"	"1.44Mb on a 3.5 or 5.25 drive" \
		"720/1440"	"720Kb  on a 3.5  drive" \
		"1200/1200"	"1.2Mb  on a 5.25 drive" \
		"720/1200"	"720Kb  on a 5.25  drive" \
		"User defined"  "Enter your own value from /etc/fdprm" \
		"<"		"Return to Device Menu" 2>$TMP/$DIALOGFILE 
	if [ $? = 0 ]
	then
		case `cat $TMP/$DIALOGFILE` in
			"<")	return
				;;
			"User definded")
				$DIALOG --inputbox \
"Please enter your own value for a floppy format description,
like specified in \"/etc/fdprm\":
" 7 75 2>$TMP/$DIALOGFILE
				if [ $? = 0 ]
				then
					tmp=`cat $TMP/$DIALOGFILE`
					if [ "$tmp" != "" ]
					then
						floppy_format="$tmp"
						Configuration_changed=YES
					fi
				fi
				;;
			*)	floppy_format=`cat $TMP/$DIALOGFILE`
				Configuration_changed=YES
				;;
		esac
	else
		return
	fi
	done
}

test_tape_device()
{
	if [ "Autodetect_src_loaded" != "YES" ]
	then
		. $SRCDIR/$AUTODETECT_SRC
	fi

	insert_media && \
	$DIALOG --title " Warning! " --yesno \
"
This test will erase any data on the tape!
Are you sure that you want to continue?" 8 50
	if [ $? = 0 ]
	then
		test_tape_device_II "$device"
		if [ $? = 0 ]
		then
			MsgBox "Your tape drive 
\"$device\" 
is compatible with KBackup."
		else
			MsgBox "Your tape drive
\"$device\"
is a rewind-on-close device and 
therefore not compatible with 
KBackup. Please choose a non-re-
winding one and try again."	
		fi
	fi
}

autodetect_tape_device()
{
	if [ "Autodetect_src_loaded" != "YES" ]
	then
		. $SRCDIR/$AUTODETECT_SRC
	fi
	autodetect_tape_device_II 
	autodetect_tape_menu
}

Device_Menu()
{
	while : ; do
		$DIALOG --title " Device Menu " --menu "\n\
Choose a device for your backup and optionally set the device related\n\
options. If you are choosing a tape drive, it must not do an automatic 
rewind at the end of a file being written.
Autodetection might not work on your system, use it with care!

Current setting: $device  Type: $device_type" 24 76 12 \
		A		"Attempt to autodetect tape device"\
		C		"Check tape drive for compatibility"\
		B		"Set block size for writing to tape [$syncto]" \
		D		"Set device type                    [$device_type]"\
		N		"Filename for backup files [$arch_filename]"\
		"Specify" 	"Enter your own device/archive file"\
		"/dev/fd0" 	"First floppy drive"\
		"/dev/fd1" 	"Second floppy drive"\
		T		" Blockdev filesystem type          [$blockdev_fs_type]"\
		M		" Blockdev make filesystem command  [$blockdev_mkfs]"\
		F		"Set Floppy format                  [$floppy_format]"\
		R		"Set device for resetting driver    [$resetdevice]"\
                W               "Set waiting time for device        [$waittime]" \
"<"		"Return to KBackup Config Menu" 2>$TMP/$DIALOGFILE
	if [ $? = 0 ]
	then
		case `cat $TMP/$DIALOGFILE` in
		A)	autodetect_tape_device
			;;
		F)	Floppy_Format_Menu
			;;
		B)
			$DIALOG --inputbox \
"Some tape drivers, e.g. ZFTAPE require date to be written
with specific block sizes. For ZFTAPE this defaults to
10240 bytes.
Here you can set the block size that KBackup will use.
Leave it empty to keep the current value, which is:
\"$syncto\"
" 15 75 2>$TMP/$DIALOGFILE
			if [ $? = 0 ] 
			then
				tmp=`cat $TMP/$DIALOGFILE`
				if [ -n "$tmp" ]
				then
					syncto=$tmp
				fi
			fi
			;;
		D)	case "$device_type" in
				TAPE)
					device_type=BLOCKDEV
					;;
				BLOCKDEV)
					device_type=FILE
					;;
				FILE)
					device_type=FLOPPY
					;;
				FLOPPY)
					device_type=TAPE
					;;
			esac
			Configuration_changed=YES
			;;
		  W)
 			$DIALOG   --inputbox "Please specify time to wait in seconds for device IO.\n(default: $waittime)" 9 75 2>$TMP/$DIALOGFILE
			if [ $? = 0 ]
			then
				tmp=`cat $TMP/$DIALOGFILE`
				if [ -n "$tmp" -a "$tmp" -ge 0 ] 2>/dev/null
				then
					waittime=$tmp
					Configuration_changed=YES
				fi
			fi
			;;
		N)
			$DIALOG --inputbox \
"For using archive files or for having more than one archive on a
mounted block device, you can here specify an archive name to use.
When restoring the archive, you need to use the same archive name.
However, this is easily to obtain (just look at the directory) and
future versions of KBackup might even provide a filerequester for it.

For the BLOCKDEV archive type, enter a short name, which will be used
relative to the mount point, e.g. \"myarchive\", \"foo-bar\",...
For the FILE archive type, enter a full pathname for the archive, e.g.
\"/mnt/backups/myarchive\", \"/nfs/bigdisk/foo-bar\",...

Leave it empty to keep the current values, which is:
\"$arch_filename\"
" 22 75 2>$TMP/$DIALOGFILE
			if [ $? = 0 ] 
			then
				tmp=`cat $TMP/$DIALOGFILE`
				if [ -n "$tmp" ]
				then
					arch_filename="$tmp"
					Configuration_changed=YES
				fi
			fi
			;;
		/dev/fd0|/dev/fd1)
			device_type=FLOPPY
			device=`cat $TMP/$DIALOGFILE`
			Configuration_changed=YES
			Floppy_Format_Menu
			;;
		Specify)	$DIALOG   --inputbox "Please specify the device/file to use.\n(default: $device)" \
			9 75 2>$TMP/$DIALOGFILE
			if [ $? = 0 ]
			then
				newdevice=`cat $TMP/$DIALOGFILE`
				if [ -n "$newdevice" ]
				then
					device="$newdevice"
					Configuration_changed=YES
				fi
				if [ -c "$device" ] ; then
					device_type=TAPE
					MsgBox "You specified a character device,\nassuming it is a tape streamer."
				else
					if [ -L "$device" ] ; then
						device_type=TAPE
						MsgBox "You specified a symbolic link,\nassuming it is a tape streamer."
					else
						if [ -b "$device" ] ; then
							device_type=FLOPPY
							MsgBox "You specified a block device,\nassuming it is a floppy drive."
						fi
					fi
				fi
			fi
			;;
		R)	$DIALOG   --inputbox "Please specify the device for resetting the driver:\n(default: $resetdevice)\nThis seems to work only with the QIC02-driver!\n" \
			11 75 2>$TMP/$DIALOGFILE
			if [ $? = 0 ] && test -n "`cat $TMP/$DIALOGFILE`"
			then
				if [ -c `cat $TMP/$DIALOGFILE` ] ; then
					resetdevice=`cat $TMP/$DIALOGFILE`
					Configuration_changed=YES
				else
					$DIALOG   --msgbox "\nNo character device!\nKeeping old value." 5 40
				fi
			fi
			;;
		"<")	return
			;;
		T)	$DIALOG --title " Filesystem type for mountable block devices " \
				--inputbox \
"Please specify the filesystem type to use on the block
device. KBackup will automatically format and error check
every backup medium.

Recommended: \"minix\" on floppies, \"ext2\" for removable
hard drives.
"  14 75 2>$TMP/$DIALOGFILE
			if [ $? = 0 ]
			then
				tmp=`cat $TMP/$DIALOGFILE`
				if [ "$tmp" != "" ]
				then
					blockdev_fs_type="$tmp"
					Configuration_changed=YES
				fi
			fi
			;;				
		M)	$DIALOG --title " Formatting command for mountable block devices " \
			--inputbox \
"Please specify the command to execute for formatting a block device. 
KBackup will automatically create a filesystem on every medium and 
afterwards mount it, using the current filesystem setting. Of course, 
the formatting command must match the setting for the filesystem type.

Current filesystem type setting: \"$blockdev_fs_type\"

The string \$device will be changed into the actual device name.

Suggested values:
	mkfs -t minix \$device nblocks   : to create a minix fs
	mkfs -t ext2 \$device		 : to create an ext2 fs
	fdformat \$device && mkfs -t minix \$device 
 		: to low-level format a floppy and put a minix fs on it
 		
(Just press ENTER to keep the current value.)" 23 75 2>$TMP/$DIALOGFILE
		if [ $? = 0 ]
		then
			tmp=`cat $TMP/$DIALOGFILE`
			if [ "$tmp" != "" ]
			then
				blockdev_mkfs="$tmp"
				Configuration_changed=YES
			fi
		fi
		;;
		C)	# check tape drive for compatibility
			test_tape_device
		;;
		esac
	else
		return
	fi
	done
}

Multivolume_Menu()
{
	while : ; do
		$DIALOG --title " MultiBuf Options Menu " --menu "
Options relevant for handling archives that span more than one
physical volume and for double buffering.
The MultiBuf program is able to automatically detect the end of a 
backup medium and will prompt you to change it. It also adds se-
quence information to the archive, preventing you from using the 
backup media in the wrong order when restoring. Furtheron it can
double-buffer the data stream to keep your tape drive streaming
all the time.

Normally, you do not need to change these settings." 23 72 7\
			S	"Set MultiBuf blocksize                 [$multibuf_blksize]"\
			N	"Set number of MultiBuf blocks per call [$multibuf_nblocks]"\
			I	"Use sequence information in MultiBuf   [$multibuf_seq_info]"\
			E	"Set command to execute at end of tape"\
			B	"Set command to execute at begin of new tape"\
			T	"Toggle use of MultiBuf                 [$use_multibuf]"\
			"<"	"Return to Parameters Menu" 2>$TMP/$DIALOGFILE
		if [ $? = 0 ]
		then
		case `cat $TMP/$DIALOGFILE` in
			I)	if [ $multibuf_seq_info = YES ]
				then
					multibuf_seq_info=NO
				else
					multibuf_seq_info=YES
				fi
				Configuration_changed=YES
				;;
			T)	if [ "$use_multibuf" = "YES" ]
				then
					use_multibuf=NO
				else
					use_multibuf=YES
				fi
				Configuration_changed=YES
				;;
			S)	$DIALOG   --inputbox \
"Please give the size of a single block in bytes.
This should be a small kilobyte value, like e.g. 4096.
(default: $multibuf_blksize)\n" \
				11 75 2>$TMP/$DIALOGFILE
				if [ $? = 0 ]
				then
					multibuf_blksize=`cat $TMP/$DIALOGFILE`
					Configuration_changed=YES
				fi
				;;
			N)	$DIALOG   --inputbox \
"Please give the number of blocks for buffering. Multiplied with the
blocksize this should give a reasonable big buffer. The bigger it is
the less overhead it causes. The smaller it is, the more effective 
will MultiBuf use your volumes. For tapes I would recommend something
a total buffer size of 100K (blocksize=1024, number of blocks=100).
In general, the total buffer size must(!) be smaller than the size
of your volume.
(default: $multibuf_nblocks)\n"\
				16 75 2>$TMP/$DIALOGFILE 
				if [ $? = 0 ]
				then
					multibuf_nblocks=`cat $TMP/$DIALOGFILE`
					Configuration_changed=YES
				fi
				;;
			"<")	return
				;;
			E)	$DIALOG --inputbox \
"The command specified here is used by MultiBuf to either prompt
the user to change tapes or to tell an automatic loading mechanism
to change tapes. However, this command will be executed whenever
MultiBuf detects an end of tape.

If you want to use the default value, enter DEFAULT .
If you want to keep the current value, just press enter.

The current value is:
\"$multibuf_cmd1\"\n" 17 74 2>$TMP/$DIALOGFILE
				if [ $? = 0 ]
				then
					tmp=`$SED "1,$ s/\"/\\\"/g" <$TMP/$DIALOGFILE`
					if [ "$tmp" != "" ]
					then
						multibuf_cmd1="$tmp"
						Configuration_changed=YES
					fi
				fi
				;;
			B)	$DIALOG --inputbox \
"The command specified here is called by MultiBuf after the
tape has been changed. Usually, after changing tapes, you
should execute something like a \"mt rewind\".
Even if your tape is auto-rewinding any new cartridge, you
should issue the rewind command. (QIC-02 causes problems
otherwise.)

To use this default value, enter DEFAULT .
If you want to keep the current value, just press enter.

The current value is:
\"$multibuf_cmd2\"\n" 20 74 2>$TMP/$DIALOGFILE
				if [ $? = 0 ]
				then
					tmp=`$SED "1,$ s/\"/\\\"/g" <$TMP/$DIALOGFILE`
					if [ "$tmp" != "" ]
					then
						multibuf_cmd2="$tmp"
						Configuration_changed=YES
					fi
				fi
				;;

		esac
		else
			return
		fi
	done
}

				

Advanced_Options_Menu()
{

	while : ; do
		$DIALOG   --title " Advanced Options Menu " --menu "\n\
The options in this menu deeply affect the operation of KBackup. You\n\
should know what you are doing before making any changes. If you are\n\
not sure, go back to the main menu and read the manual first.\n" 20 77 8 \
			S	"Backup only files specified               [$specifiedfilesonly]"\
			N	"    Edit list of files to include in backup" \
			I	"    Initialise list of files to include" \
			X	"Set Find-Expert Mode                      [$findxpertmode]"\
			O	"Set find-options for Find-Expert Mode"\
			E	"Set option to manually edit list of files [$manualedit]"\
			D	"Toggle Directories-Only Flag              [$directoriesonly]" \
			"<"	"Return to File Selection Menu" 2>$TMP/$DIALOGFILE
		if [ $? = 0 ]
		then
		case	`cat $TMP/$DIALOGFILE` in
			D)	if [ "$directoriesonly" = "YES" ] ; then
					directoriesonly=NO
				else
					directoriesonly=YES
				fi
				Configuration_changed=YES
				;;
			S)	if [ "$specifiedfilesonly" = "YES" ] ; then
					specifiedfilesonly=NO
				else
					specifiedfilesonly=YES
				fi
				Configuration_changed=YES
				;;
			N)	$EDITOR "$datadir/$configname/Include_Files"
				;;
			I)	InfoBox "Reading files..." 
				create_dir_list
				cp -f "$TMP/$DIRLISTFILE" "$datadir/$configname/Include_Files"
				;;
			E)	if [ "$manualedit" = "YES" ] ; then
					manualedit=NO
				else
					manualedit=YES
				fi
				Configuration_changed=YES
				;;
			X)	if [ "$findxpertmode" = "YES" ] ; then
					findxpertmode=NO
				else
					findxpertmode=YES
				fi
				Configuration_changed=YES
				;;
			O)	$DIALOG   --inputbox "Please enter options for find(1) command:\n(default: $findxpertflags)"\
					11 75 2>$TMP/$DIALOGFILE
				if [ $? = 0 ]
				then
					if [ -n "`cat $TMP/$DIALOGFILE`" ]
					then
						findxpertflags="`cat $TMP/$DIALOGFILE`"
						Configuration_changed=YES
					fi
				fi
				;;
			"<")	return
			;;
		esac
		else
			return
		fi
	done
}


File_Selection_Menu()
{
	while : ; do
		$DIALOG   --title " File Selection Menu " --menu "\n\
This menu allows you to change the selection criteria for files to
be backed up.\n" 22 77 10 \
			E	"Toggle Local Filesystem Mode           [$local]" \
			I	"Toggle Incremental Mode                [$incremental]" \
			D	"Set date for incremental backup"\
			F	"Edit list of files to exclude" \
			X	"Set shell pattern for files to exclude" \
			N	"Set shell pattern for files to include" \
			T	"Toggle use of include/exclude patterns [$use_patterns]" \
			P	"Protect newer files during restore [$protect_newer]" \
			A	"Set advanced options" \
			"<"	"Return to Configuration Menu" 2>$TMP/$DIALOGFILE
		if [ $? = 0 ]
		then
		case	`cat $TMP/$DIALOGFILE` in
			E)	if [ "$local" = "YES" ] ; then
					local=NO
				else
					local=YES
				fi
				Configuration_changed=YES
				;;
			"P")	if [ "$protect_newer" = "YES" ]
				then
					protect_newer=NO
				else
					protect_newer=YES
				fi
				Configuration_changed=YES
				;;
			I)	if [ "$incremental" = "YES" ] ; then
					incremental=NO
				else
					incremental=YES
				fi
				Configuration_changed=YES
				;;
			D)	$DIALOG   --inputbox \
				"Please specify the date in MM/DD/YY HH:MM format:\n(default: \"$datestamp\"):" 9 75 2>$TMP/$DIALOGFILE
				if [ $? = 0 ]
				then
					if [ "`cat $TMP/$DIALOGFILE`" != "" ]
					then
						datestamp=`cat $TMP/$DIALOGFILE`
						Configuration_changed=YES
					fi
				fi
				;;
			F)	$EDITOR "$datadir/$configname/Exclude_Files"
				$SED "1,$ s/^\///g" <"$datadir/$configname/Exclude_Files" >$TMP/$TMPFILE 
				cat <$TMP/$TMPFILE >"$datadir/$configname/Exclude_Files" 
				;;
			X)	$EDITOR "$datadir/$configname/Exclude_Patterns"
				;;
			N)	$EDITOR "$datadir/$configname/Include_Patterns"
				;;
			T)	if [ "$use_patterns" = "NO" ]
				then
					use_patterns=YES
				else
					use_patterns=NO
				fi
				Configuration_changed=YES
				;;
			A)	Advanced_Options_Menu
				;;
			"<")	return
			;;
		esac
		else
			return
		fi
	done
}


Remote_mode_Menu()
{
	while : ; do
		$DIALOG --title " Remote Mode Menu " --menu "
Here you can set the options for accesing a remote
backup device, e.g. a tape drive on another computer
somewhere in the network.

This is still ALPHA and might not work for you!

" 23 77 5 \
		T	"Toggle use of remote mode    [$remote_mode]"\
		H	"Set hostname to connect to   [$remote_host]"\
		U	"Set user to use for login    [$remote_uid]"\
		V	"Verify whether settings work"\
		"<"	"Return to Config Menu" 2>$TMP/$DIALOGFILE
		if [ $? = 0 ]
		then
		case `cat $TMP/$DIALOGFILE` in
		T)	if [ "$remote_mode" = "YES" ] ; then
				remote_mode=NO ; else
				remote_mode=YES;
			fi
			Configuration_changed=YES
			;;
		H)	$DIALOG --inputbox "Please specify the host to connect to:" \
			9 75 2>$TMP/$DIALOGFILE 
			if [ $? = 0 ] && test -n "`cat $TMP/$DIALOGFILE`"
				then
					remote_host=`cat $TMP/$DIALOGFILE`
					Configuration_changed=YES
				fi
			;;
		U)	$DIALOG --inputbox "\
Please specify the username to use for connecting to the remote host. 
The user must have write access to the backup device. The user must
also be existent on this machine as well as the remote one and allow
remote login using rsh(1) without password prompting.

(A setting that works fine for me, is to use adm as the username and
put the computer KBackup is running on into the /ets/hosts.equiv file
of the remote computer, to allow rsh(1) to work.)

NOTE: The MultiBuf program must be available on the remote computer!

" 23 75 2>$TMP/$DIALOGFILE 
			if [ $? = 0 ] && test -n "`cat $TMP/$DIALOGFILE`"
			then
				remote_uid=`cat $TMP/$DIALOGFILE`
				Configuration_changed=YES
			fi
			;;
		V)	InfoBox "Changing my user ID..."
			su "$remote_uid" -c echo 2>$STDERR 1>/dev/null
			check_error
			if [ $? != 0 ] ; then break ; fi
			
			InfoBox "Trying to connect..."
			su "$remote_uid" -c "rsh $remote_host echo" 2>$STDERR 1>/dev/null
			check_error
			if [ $? != 0 ] ; then break ; fi
			
			InfoBox "Checking device..."
			su "$remote_uid" -c "rsh $remote_host \"test -w $device\" " 2>$STDERR 
			check_error
			if [ $? != 0 ] ; then
				MsgBox "Unable to open device for writing."
			fi
			;;
		"<")	return
			;;
		esac
		fi
	done
}

Archive_Type_Menu()
{
	while : ; do
		$DIALOG --title " Archive Type Menu " --menu \
"KBackup can use either tar(1) or afio(1) to handle its archives.
Using these well tested programs ensures compatibility across
platforms and high reliability.
Tar is the more tested and portable one, while afio offers much
improved functionality, especially when used with encryption or
compression. Using comrpression with tar is unsafe.

Currently set archive handler: $archive_format
" 21 77 5 \
			A	"Use Afio"\
			T	"Use Tar" \
			F	"Set additional command line parameters for Afio" \
			R	"Set additional command line parameters for Tar" \
			"<"	"Return to Configure KBackup Menu" 2>$TMP/$DIALOGFILE
		if [ $? = 0 ]
		then
		case	`cat $TMP/$DIALOGFILE` in
			A)	archive_format=AFIO
				Configuration_changed=YES
				;;
			T)	archive_format=TAR
				Configuration_changed=YES
				;;
			F)	$DIALOG   --inputbox \
"Additional command line parameters to pass to Afio:
(Current setting: \"$afio_user_opts\")
Enter a single space for no options, press ENTER to keep
existing ones." \
				12 75 2>$TMP/$DIALOGFILE
				if [ $? = 0 ] && test -n "`cat $TMP/$DIALOGFILE`"
				then
					afio_user_opts=`cat $TMP/$DIALOGFILE`
					Configuration_changed=YES
				fi
				;;
			R)	$DIALOG   --inputbox \
"Additional command line parameters to pass to Tar:
(Current setting: \"$tar_user_opts\")
Enter a single space for no options, press ENTER to keep
existing ones." \
				12 75 2>$TMP/$DIALOGFILE
				if [ $? = 0 ] && test -n "`cat $TMP/$DIALOGFILE`"
				then
					tar_user_opts=`cat $TMP/$DIALOGFILE`
					Configuration_changed=YES
				fi
				;;
			"<")	return
				;;
		esac
		else
			return
		fi
	done
}

Config_KBackup_Menu()
{
	while : ; do
		$DIALOG --title " Config KBackup Menu " --menu "" 24 77 17 \
			C	"Create Report on Backup                 [$CreateReport]"\
			E	"Set name of editor to use               [$EDITOR]" \
			F	"Follow backup/restore-process on screen [$followtarops]"\
			L	"Toggle creation of restore-log file     [$restore_write_log]"\
			P	"Set compression/encryption mode         [$compression, Opt:\"$compress_options\"]"\
			B	"Toggle use of double buffering          [$double_buffering]"\
 			S	"Set # of buffers for double buffering   [$ddbufsize]"\
			U	"MultiBuf Options Menu"\
			V	"Verify archive after writing            [$verify_archive]"\
			Y	"Archive Type Menu                       [$archive_format]"\
			T	"Change KBackup directory                [$datadir]"\
			D	"Select device/type for backup           [$device_type]"\
			W	"Toggle Auto-Rewind                      [$AutoRewind]"\
			R	"Remote mode settings"\
			M	"Set directory for temporary files       [$TMP]"\
			O	"Set command for viewing online manual"\
			"<"	"Return to Configuration Menu" 2>$TMP/$DIALOGFILE
		if [ $? = 0 ]
		then
		case	`cat $TMP/$DIALOGFILE` in
			C)	$DIALOG   --title  " Report Creation" --inputbox "
KBackup can create a report of the backup creation
and optionally mail it to someone or print it.

Here you can give the command to pass the report to, e.g.:

  \"lpr\"              -- this will simply print the report
  \"mail sysadmin\"    -- this will mail it to \"sysadmin\"
  \"cat >/tmp/report\" -- this will save it in \"/tmp/report\"

Just press ENTER if you want to discard the report.
" 20 65 2>$TMP/$DIALOGFILE
			if [ $? = 0 ]
			then
				tmp=`cat $TMP/$DIALOGFILE`
				if [ "$tmp" != "" ]
				then
					Configuration_changed=YES
					ReportCommand="$tmp"
					CreateReport=YES
				else
					CreateReport=NO
				fi
			else
				CreateReport=NO
			fi
			;;
			E)	$DIALOG   --inputbox "Please specify the editor you want to use:" \
					9 75 2>$TMP/$DIALOGFILE
				if [ $? = 0 ] && test -n "`cat $TMP/$DIALOGFILE`"
				then
					EDITOR=`cat $TMP/$DIALOGFILE`
					Configuration_changed=YES
				fi
				;;
			R)	Remote_mode_Menu
				;;
			F)	if [ "$followtarops" = "YES" ] ; then
					followtarops=NO
				else
					followtarops=YES
				fi
				Configuration_changed=YES
				;;
			L)	if [ "$restore_write_log" = "YES" ] ; then
					restore_write_log=NO
				else
					restore_write_log=YES
				fi
				Configuration_changed=YES
				;;

			P)	Compression_Menu
				;;
			V)	if [ "$verify_archive" = "YES" ]
				then
					verify_archive=NO
				else
					verify_archive=YES
				fi
				Configuration_changed=YES
				;;
			Y)	Archive_Type_Menu
				;;
			U)	Multivolume_Menu
				;;
			B)	if [ "$double_buffering" = "YES" ] ; then
					double_buffering=NO
				else
					double_buffering=YES
				fi
				Configuration_changed=YES
				;;
			S)	$DIALOG   --inputbox "Please enter number of buffers for multi buffering.\n(e.g. 2,10)" \
				9 75 2>$TMP/$DIALOGFILE
				if [ $? = 0 ] && test -n "`cat $TMP/$DIALOGFILE`"
				then
					ddbufsize=`cat $TMP/$DIALOGFILE`
					if [ ! "$ddbufsize" -gt 2 ] 2>/dev/null ; then
						ddbufsize=2
						Configuration_changed=YES
					fi
				fi
				;;
			T)	$DIALOG   --inputbox "Please enter the KBackup directory (default: ~/$KBACKDIRDEFAULT)" \
				9 75 2>$TMP/$DIALOGFILE
				if [ $? = 0 ] && test -n "`cat $TMP/$DIALOGFILE`"
				then
					datadir=`cat $TMP/$DIALOGFILE`
					Configuration_changed=YES
				fi
				;;
			M)	$DIALOG   --inputbox "Please enter the directory for temporary files:" \
				9 75 2>$TMP/$DIALOGFILE
				if [ $? = 0 ] && test -n "`cat $TMP/$DIALOGFILE`"
				then
					tmp=`cat $TMP/$DIALOGFILE`
					if [ -d "$tmp" -a -w "$tmp" ]
					then
						changeTMP "$tmp"
						Configuration_changed=YES
					else
						ErrorBox "Cannot access \"$tmp\" as a directory."
					fi
				fi
				;;
			D)	Device_Menu
				;;
			O)	$DIALOG --title " Online Menu Command " --inputbox "
Please specify the command for viewing the Online Manual.
Examples are:
   less $docdir/manual.asc
   dialog --textbox $docdir/manual.asc 24 77
   lynx $docdir/whtml/KBackup.html
   netscape $docdir/html/KBackup.html
Current setting: $manual_command" 15 75 2>$TMP/$DIALOGFILE
				if [ $? = 0 ]
				then
					if [ "`cat $TMP/$DIALOGFILE`" != "" ]
					then
						manual_command=`cat $TMP/$DIALOGFILE`
						Configuration_changed=YES
					fi
				fi
				;;
			"W")	if [ "$device_type" != "TAPE" ]
				then
					ErrorBox "This option does only make sense
when using a tape drive."
				else
					if [ "$AutoRewind" = "YES" ]
					then
						AutoRewind=NO
					else
						AutoRewind=YES
						MsgBox "You have activated the Auto-Rewind
option. 
Please do not use this if you want 
to write multiple archives on one 
tape."
					fi
					Configuration_changed=YES
				fi
				;;
			"<")	return
				;;
		esac
		else
			return
		fi
	done
}

Write_Config()
{
	Check_Settings
	$DIALOG   --inputbox "Please specify a unique name for this configuration:\nThe current name is:\n\"$configname\"\nJust press RETURN to keep this name." \
		13 75 2>$TMP/$DIALOGFILE
	if [ $? = 0 ] 
	then
		oldconfig="$configname"
		configname=`cat $TMP/$DIALOGFILE`
		if [ "$configname" = "" ]
		then
			configname="$oldconfig"
		fi
		if [ -d $datadir/$configname ]
		then
			$DIALOG --yesno \
				"A configuration named\n$configname\ndoes already exist!\n\nOverwrite it with new settings?" 9 40 
			if [ $? = 0 ]
			then
				save_config
				Configuration_changed=NO
			else
				MsgBox "Write Configuration aborted."
			fi
		else
			save_config
			Configuration_changed=NO
		fi
	fi
}
Configuration_Menu()
{
	while : ; do
		$DIALOG   --title " Configuration Menu " --menu "\n\
Choose \"Configure KBackup\" for options that determine how KBackup
works; choose \"Set file selection parameters\" for deciding which
files to include in the backup.
\nThe current configuration is \"$configname\".\n\
The current parent directory is \"$parent\"." 21 77 7 \
			P	"Set parent directory for backup/restore " \
			F	"Set file selection parameters" \
			C	"Configure KBackup" \
			W	"Write a configuration file" \
			L	"Load a configuration file" \
			D	"Delete a configuration file"\
			"<"	"Return to main menu" 2>$TMP/$DIALOGFILE
		if [ $? = 0 ]
		then
		case	`cat $TMP/$DIALOGFILE` in
			F)	File_Selection_Menu
				;;
			C)	Config_KBackup_Menu
				;;
			P)	choose_dir $parent
				parent="$choose_dir_result"
				Configuration_changed=YES
				;;
			W)	Write_Config
				;;
			L)	find "$datadir"/* -type d -prune -printf "%f %Tx\n" |\
					$FGREP -v "$KBACKDIRDEFAULT" | sort >$TMP/$TMPFILE
				lines=`$WC -l <$TMP/$TMPFILE`
				if [ "$lines" -gt 15 ] ; then lines=15 ; fi
				$DIALOG   --menu "Choose a configuration:" 22 \
				60 $lines `cat $TMP/$TMPFILE` 2>$TMP/$DIALOGFILE
				if [ $? = 0 ]
				then
					ConfigNumVersion=0
					. $datadir/`cat $TMP/$DIALOGFILE`/Config
					changeTMP "$TMP"
					if [ $ConfigNumVersion = 0 ]
					then
						ddbufsize=2
					fi
					Configuration_changed=YES
				fi
				;;
			D)	find "$datadir"/* -type d -prune -printf "%f %Tx\n" |\
					$FGREP -v "$KBACKDIRDEFAULT" | sort >$TMP/$TMPFILE
				lines=`$WC -l <$TMP/$TMPFILE`
				if [ "$lines" -gt 15 ] ; then lines=15 ; fi
				$DIALOG --menu "Choose a configuration to
				delete:" 20 60 $lines \
					`cat $TMP/$TMPFILE` 2>$TMP/$DIALOGFILE
				if [ $? = 0 ]
				then
					rm -rf $datadir/`cat $TMP/$DIALOGFILE`
				fi
				;;
			"<")	Check_Settings
				return
			;;
		esac
		else
			Check_Settings
			return
		fi
	done
}

Goto_Nth()
{
	$DIALOG   --inputbox "Please give the number of the backup to go to:" 9 75 2>$TMP/$DIALOGFILE
	if [ $? = 0 ]
	then
		num=`cat $TMP/$DIALOGFILE`
		test $num -gt 0 2>/dev/null # is it a positive number?
		if [ $? != 0 ]
		then
			ErrorBox "No valid backup number!"
			return
		fi
		if [ "$remote_mode" = YES ]
		then
			su "$remote_uid" -c "rsh $remote_host ls -l $device" | sed '1,$ s/.* \([0-9]*\),.*/\1/g' >$TMP/$TMPFILE 2>$STDERR
		else
			ls -l "$device" | sed '1,$ s/.* \([0-9]*\),.*/\1/g' >$TMP/$TMPFILE 2>$STDERR
		fi
		check_error
		if [ $? != 0 ] ; then break ; fi
		InfoBox "Rewinding tape..." 
		my_mt -f "$device" rewind
		mysleep 5
		my_mt -f "$device" rewind
		pos=1
		while [ $pos -lt $num ]
		do
                	cat < "$device" >$TMP/$TMPFILE 2>$STDERR # read header
                	check_error -dev
                	if [ $? != 0 ]
                	then
                	        return
                	else
                	        if read firstline < $TMP/$TMPFILE && [ "$firstline" = "#KBackup" ]
                	        then
                	                . $TMP/$TMPFILE
                	        else
                	                ErrorBox "No valid KBackup Archive Header.
Goto failed."
                	                return
                	        fi
			fi
			skip=`expr $backup_filesperarchive - 1`
			InfoBox "Skipping backup #$pos..."
			last_command="mt -f \"$device\" fsf $skip"
			my_mt -f "$device" fsf $skip 2>$STDERR
			check_err -dev
			pos=`expr $pos + 1`
		done
	fi
}


Tape_Operation_Menu()
{
	if [ "$device_type" != "TAPE" ] ; then
		ErrorBox \
"You can only perform these operations on a device
that is a tape drive, not on an archive file or 
floppy drive!"
		return
	fi
	
	while :
	do
	$DIALOG   --title " Operations on Tape Drives " --menu \
"
This menu is a frontend to the mt(1) command
for executing tape drive specific operations.
" 19 51 8\
		R	"Rewind tape" \
		D	"Reset tape driver (QIC02 driver only)" \
		G	"Go to n-th backup on tape" \
		N	"Go to end of written data"\
		E	"Erase tape" \
		T	"Retension tape" \
		O	"Set tape offline: rewind and unload it"\
		"<"	"Return to Actions Menu" 2>$TMP/$DIALOGFILE
	if [ $? = 0 ]
	then
	  case `cat $TMP/$DIALOGFILE` in
	    R)
	       InfoBox "Rewinding tape..." 
	       my_mt -f "$device" rewind 2>$STDERR
	       mysleep 5
	       my_mt -f "$device" rewind 2>$STDERR
	       check_error -dev
	       ;;
	    D)
	       InfoBox "Resetting tape driver..." 
	       cat <"$resetdevice" 2>/dev/null
	       ;;
	    G)
	       Goto_Nth
	       ;;
	    N)
	       InfoBox "Searching for end of data..." 
	       my_mt -f "$device" eom 2>$STDERR # mt-GNU
	       if [ $? = 1 ]
	       then
		 last_command="mt -f \"$device\" seod"
		 my_mt -f "$device" seod 2>$STDERR # mt-st
	       fi
	       check_error -dev
	       ;;
	    O)
	       InfoBox "Telling device to go offline..."
	       my_mt -f "$device" offline 2>$STDERR
	       check_error -dev
	       ;;
	    E)
	       beep
	       $DIALOG   --title " DANGEROUS! " --yesno "
	       Do you really want to erase the
	       whole tape?

	       WARNING: This might take very
	       long, especially on DAT drives!
	       " 11 40 2>$TMP/$DIALOGFILE
	       if [ $? = 0 ]
	       then
		 InfoBox "Erasing tape..." 
		 my_mt -f "$device" erase  2>$STDERR
		 check_error -dev
	       fi
	       ;;
	    T)
	       InfoBox "Retensioning tape..."
	       my_mt -f "$device" reten 
	       auto_rewind
	       check_error -dev
	       ;;
	    "<")
		 return
		 ;;
	  esac
	else
		return
	fi
	done
}

Actions_Menu()
{
	while :
	do
	$DIALOG   --title " Actions Menu " --menu "\n\
Actions, apart from backup and restore,\nthat operate on archives.\n" 18 45 8 \
		T	"Tape Operation" \
		V	"Verify backup" \
		S	"Get backup size" \
		C	"View archive contents" \
		L	"View a logfile"\
		D	"Delete a logfile"\
		B	"Send a bug report" \
		"<"	"Return to main menu" 2>$TMP/$DIALOGFILE
	if [ $? = 0 ]
	then
		case `cat $TMP/$DIALOGFILE` in
			V)	Verify
				auto_rewind
				;;
			C)	View_Contents
				auto_rewind
				;;
			S)	Get_BackupSize
				;;
			L)	View_Logfile
				;;
			D)	Delete_Logfile
				;;
			T)	Tape_Operation_Menu
				;;
		  B)
		     bugreport=N
				while :
				do
				  $DIALOG --title " Bug Report " --menu \
				   "You are having problems with KBackup?

Before submitting a bug report, PLEASE read the documentation
coming with KBackup. Most problems reported are covered there.

Also, please note that I can only answer to KBackup specific
problems. If you do not know how to get your drive working (
especially if you are crazy enought to trust ftape), do not
ask me about that.

If you have a problem with KBackup itself, want to suggest an
improvement, or (best of all) submit a bugfix, go ahead." 23 70 4 \
                                        "W"     "Write bug report" \
					"M"	"Mail bug report to author"\
					"S"	"Save bug report in a file" \
					"<"	"Back to Actions Menu" 2>$TMP/$DIALOGFILE
					if [ $? != 0 ]
					then
						return	# sigint
					fi
					case `cat $TMP/$DIALOGFILE` in
					"W")
		     echo -e "Subject: KBackup $VERSION bug report\n(Please fill in the form below:)\n\
			
Problem description:\n\n\n\
-------------------------- KBackup configuration: -------------------------\n\
" >$TMP/$MAILFILE

				write_settings >>$TMP/$MAILFILE
				echo -e "
-------------------------- System information: ----------------------------\n\
" >>$TMP/$MAILFILE
				uname -a >>$TMP/$MAILFILE
				cat /proc/devices >>$TMP/$MAILFILE
				$EDITOR $TMP/$MAILFILE
				bugreport=Y
				;;
					  "M") if [ "$bugreport" = Y ]
					       then
					       $MAIL $MAILADDRESS <$TMP/$MAILFILE
						if [ $? != 0 ]
						then
							ErrorBox "Could not send bugreport.\n($MAIL missing?) "
						else
							MsgBox "Bugreport sent."
						fi
					  else
					    ErrorBox "You must write it first!"
					    fi
						;;
					"S") 	 if [ "$bugreport" = Y ]
					       then
					      $DIALOG --title " Bug Report "  --inputbox \
						"Filename to write to:" 9 75 2>$TMP/$DIALOGFILE 
						if [ $? = 0 ] && [ -n `cat $TMP/$DIALOGFILE` ]
						then
							cat $TMP/$MAILFILE > `cat $TMP/$DIALOGFILE`
						fi
					  else
					    ErrorBox "You must write it first!"
					    fi
						;;
					"<")	break
						;;
					esac
				done
				;;
			"<")	return
				;;
		esac
	else
		return
	fi
	done
}

view_manual()
{
	$manual_command
	if [ "$?" != 0 -a "$?" != 255 ]
	then
		ErrorBox "Cannot access online manual via \n\"$manual_command\""
	fi
}

#
# check whether anything is necessary in case CTRL-C was pressed
#
main_level_cleanup()
{
	if [ "$device_type" = "BLOCKDEV" ]
	then
		InfoBox "Trying to unmount device..."
		umount "$MOUNTPOINT" 2>/dev/null
	fi
}


############################## MAIN MENU ###########################

Main_Menu()
{
	while : ; do
	$DIALOG   --title " KBackup $VERSION -- Main Menu " \
	--menu "\nThe current configuration is:\n$configname" 17 35 7 \
		C	"Configuration" \
		B	"Backup" \
		R	"Restore" \
		A	"Other Actions" \
		S	"Scheduling menu"\
		H	"Help -- view online manual" \
		X	"Exit"	2>$TMP/$DIALOGFILE
	if [ $? = 0 ]
	then
		case `cat $TMP/$DIALOGFILE` in
			C)	Configuration_Menu
				check_config_changed
				;;
			A)	Actions_Menu
				;;
			B)	Backup
				main_level_cleanup
				auto_rewind
				;;
			R)	Restore
				main_level_cleanup
				auto_rewind
				;;
			S)	do_schedule
				check_config_changed
				;;
			H)	view_manual
				;;
			X)	check_config_changed
				cleanup
				reset
				clear
				return	
				;;
		esac
	else
		return
	fi
	done
}


################# OPTIONS PROCESSING ######################

nargs="$#"
while [ "$nargs" -gt 0 ] 
do
	opt=$1
	case $opt in
		"--ttymode")
			shift
			TTYMODE=YES
			nargs=`expr $nargs - 1`
			;;
		"--scheduled-restore"|"--auto-restore")
			shift
			schedulename="$1"
			shift
			configname="$schedulename"
			scheduled=YES
			Init
			scheduled=YES
			Restore
			unschedule
			exit
			;;
		"--scheduled-backup"|"--auto-backup")
			shift
			schedulename="$1"
			shift
			configname="$schedulename"
			scheduled=YES
			Init
			scheduled=YES
			Backup
			unschedule
			exit
			;;
		*)	echo Unknown argument: $opt
			cat <<__EOF__
Allowed options are:

--ttymode	      : do not use dialog(1) program for input/output
--auto-backup XXX     : do an automatic backup with configuration XXX 
--auto-restore XXX    : do an automatic restore with configuration XXX 

__EOF__
			exit 
			;;
	esac
done


Init

clear

$DIALOG   --title "Welcome to KBackup" --msgbox \
"     #    #  ######
     #   #   #     #    ##     ####   #    #  #    #  #####
     #  #    #     #   #  #   #    #  #   #   #    #  #    #
     ###     ######   #    #  #       ####    #    #  #    #
     #  #    #     #  ######  #       #  #    #    #  #####
     #   #   #     #  #    #  #    #  #   #   #    #  #
     #    #  ######   #    #   ####   #    #   ####   #

     Version $VERSION   

   Copyright (c) 1995 - 1997 Karsten Ballueder (Ballueder@usa.net)

   KBackup comes with ABSOLUTELY NO WARRANTY; for details see the
   file COPYING or the documentation
   This is free software, and you are welcome to redistribute it
   under the terms and conditions of the GPL, version 2, as it comes
   with this package. 
	    
	To contact the maintainer, send e-mail to: KBackup@usa.net
	Visit the KBackup homepage at: http://KBackup.home.ml.org/
	    
    Karsten Ballder, Lessingstrasse 2, 32756 Detmold, Germany
" 24 70

trap "echo \"SIGINT caught, trying to leave subroutine...\" >&2 ; return 128 " SIGINT
Main_Menu

cleanup

