#!/bin/sh

#This is where all history files are stored /////
logpath=/var/adm/dump


if [ -z $1 ] || [ $1 = -h ] || [ $1 = --help ] 
then 
cat <<EOHELP

# This script implements incremental and/or compressed 
# and/or encrypted backups  using afio, gzip and pgp/gnupg on floppies 
# or tapes or other devices.

# Make sure that you have all the priviledges needed to access your files 
# and devices or start this script as root.

# USAGE:      secbak <level> [<label>]"
#     <level> = 0      :  fullbackup"
#     <level> = [1-9]  :  incremental backup" 
#
#
# EXAMPLE:    secbak 5 Tape3-

# Grep for "////" to configure this script for your environnement.
# In the function CHOOSEFILE you decide "WHAT" has to be backuped und
# in START you determine "HOW" and "WHERE".  
# For more detailed information type: 
#             secbak --help

EOHELP
if [ -z $1 ] 
then 
exit 0
fi

cat <<EOHELP

# OUTPUT and LOGFILES:
#secbak writes log-files in the \$logpath directory that may look like:
#

# a) Logfiles after normal termination of afio:
#	Tape3-1234starttime.level6 	  
#		: the ctime stamp of this file is used in later 
#		: backups for finding newer files
#	Tape3-1234filelist.level6.gz  
#		: a list of 
#		: all files archived at the time indicated by 
#		: the ctime stamp of Tape3-1234starttime.level6 
#		: (compressed with gzip)
#	Tape3-1234afiolog.level6.gz  
#		: afios messages 
#		: (compressed with gzip)

# b) Logfiles after errors
#	Tape3-2345starttimeNOT-OK.level6
#		: due to an error secbak hasn't terminated. The backup
#		: may be uncomplete  
#	Tape3-1234filelistNOT-OK.level6  
#		: a list of 
#		: all files archived at the time indicated by 
#		: the ctime stamp of Tape3-1234starttimeNOT-OK.level6 
#		: After a broken pipe this list contains usually more
#		: files than has been actually saved.
#	Tape3-2345afiologNOT-OK.level6	  
#		: afios messages

# c) general logging: 
#	backuphistory.txt
#		: All output of secbak is appended to  
#		: "backuphistory.txt". You will find there
#		: information about each backup concerning 
#		: time, error messages, the parameters afio was
#		: called with (including the device the archive
#		: archive was written on) and other usefull things. 
#				  


# RESTORING

# You don't need this script to restore the contents of the archive-files.
# You only need having afio installed and eventually gzip, pgp or gpg. 
# Since afio is compatible with cpio you can also une cpio to retore your
# archives. In this case it may be necessary to unzip the files manually.
# This may be usefull after a disc crash.

# You should  invoke afio with the parameters corresponding to the ones you 
# have used for backup. See the START-function in this script. 
# Some examples can be found in the "secbakrestore" script that 
# comes with "secbak".

# To rebuild the latest status of your disk
# start restoring the latest level 0 backup,
# then all level 1 backups, up to the 
# highest level you find in the $logpath directory.
# Keep in mind that incremental archives do not
# contain a list of in the meantime deleted files.


# REQUEST FOR HELP 
#
# This helptext and the following messages (english spelling and expression) 
# need to be revised by a native speaker.
EOHELP
exit 0
fi


# HISTORY
 
# Script written by Jens Getreu 
# New feature in secbak 1.4:			
# secbak accepts a new second optional parameter: <label>
#
# usage:      secbak <level> [<label>]
# example:    secbak 5 Tape3-
#
# The paramater label only affects the names of the logfiles given
# to the current job.
# The above example performs a level 5 backup and writes its logfiles
# in files of style: Tape3-id3456 ... .level5
#						Jens Getreu

# Version 1.5 					
# secbak 1.4 stopped in case of a return code other then 0.
# secbak 1.5 ignores the return code of afio, but tries to
# grep error messages in it's logfile instead.
#						Jens Getreu

# Version 1.6
# All pgp second input stream handling is transfered from the 
# BACKMEUP-function to the start function.
# All pgp related stuff is now kept together. 
# The pgp examples now use the afio option -3 introduced in
# afio 2.4.6.
# Examples for encryption with gpg are also introduced in 
# function "START" within 1.6.
#
# The find output is now logged in ...filelist.level...
# while afios messages are still logged in ...afiolog.level...
#
# afios return-code seems to be more relieable now. 
# secback 1.6 refers to it in order to decide whether 
# or not the backup has been successfull.
# 	16.9.1999				Jens Getreu

# Version 1.7 
# Bug in pgp commandline in START removed.
# The shell expanded "$PGPPASSFD<$passphrasefile" to "3 </foo/foofoo"
# instead of "3</foo/foofoo" what was intended.
# So I replaced "$PGPPASSFD<$passphrasefile" with "3<$passphrasefile".
# Thanks to Koen Holtman for having discoverd this.
# 	23.9.1999				Jens Getreu
 

########################## CHOOSEFILES ##########################

########## begin of uncomment one example only 

#CHOOSEFILES ()
#{
###  adapt this to fit your application /////
###  $findadd has to be  be added at the end of each find command !!!
# find /boot /etc /home /opt /root /usr/local \
#      /var/spool /var/log /var/adm/dump $findadd \
# |egrep -v '/Sicherungskopie|~$|/~|\$$|\.bak$|\.tmp$|\.tmpdir/' -
#}

CHOOSEFILES ()
{
##  adapt this to fit your application /////
##  $findadd has to be be added at the end of each find command !!!
( find /usr/local/bak /etc\
                /home/getreu/JENS_DATEN/DOKUMENTE $findadd
  find  /home/getreu/ /home/getreu/Mail /home/getreu/Emailadressen \
        /root /root/bin -maxdepth 1 $findadd) \
  |egrep -v '/Sicherungskopie|~$|/~|\$$|\.bak$|\.tmp$|\.tmpdir$' -
}
########## end of uncomment one example only 

##################### end of CHOOSEFILES #####################






########################## BACKMEUP ###########################
BACKMEUP ()
{
# There is probably no need to change anything in this function

case  $level in
  0)	# If it is a level 0 dump simply dump everything...
	findadd=''
	;;
  [1-9]) 
	# Get the date of the most recent dump with the highest level <= $level]
	prevdump=$(ls --sort=time --format=single-column \
		$logpath/*starttime.level[0-$level]| head --lines=1 \
		2>/dev/null)

	if [ -z $prevdump ]
	then
		echo "WARNING No lower level backup than $level!" 
		echo Trying backup level 0.
		level=0
		START
		echo ')'
		exit 0
	fi

	# Otherwise dump only stuff newer...
	echo "Incremental level $level backup. Previous was:" 
	echo -e "\t $prevdump"
	findadd="-cnewer $prevdump"
	;;
esac




echo "Writing filelist in:" 
echo -e "\t $logpath/${LABEL}id$$filelistNOT-OK.level${level}" 
echo "and afios (error)  messages in:" 
echo -e "\t $logpath/${LABEL}id$$afiologNOT-OK.level${level}" 
echo $1 >"$logpath/${LABEL}id$$afiologNOT-OK.level${level}" 

#save startime in timestamp of file
echo > "$logpath/${LABEL}id$$starttimeNOT-OK.level$level"

echo "Starting Backup ..."
echo \"$1\"



error=false
CHOOSEFILES |tee $logpath/${LABEL}id$$filelistNOT-OK.level${level} \
	|nice -n -15  $1 \
	1>>$logpath/${LABEL}id$$afiologNOT-OK.level${level} \
	2>&1 \
	|| error=true 



if [ $error = true ] 
	then 	echo '***ERRORs occurred!' \
		      'Your backup was probably NOT successfull***'
	     	echo "afios last 5 messages:"
		grep '^afio:' "$logpath/${LABEL}id$$afiologNOT-OK.level$level" \
			| tail --lines 5
		echo ')' 
		exit 1
	else 	echo "... Backup finished"
		echo "Here are afios messages:"
		grep '^afio:' "$logpath/${LABEL}id$$afiologNOT-OK.level$level"
fi


# All higher level backups are now invalidated so we delete logs
if [ $level -le 8 ]
  then
	# don't enclosure rm argument with ""!
	rm -f $logpath/*.level[$(($level+1))-9]*
fi


echo -e "compressing\t afiologNOT-OK.level$level"\
	"\t into: afiolog.level${level}.gz"
echo -e "\t and \t filelistNOT-OK.level$level"\
	"\t into: filelist.level${level}.gz"
gzip -c "$logpath/${LABEL}id$$afiologNOT-OK.level$level" \
	> "$logpath/${LABEL}id$$afiolog.level${level}.gz" \
	&& rm -f "$logpath/${LABEL}id$$afiologNOT-OK.level$level"


gzip -c "$logpath/${LABEL}id$$filelistNOT-OK.level$level" \
	> "$logpath/${LABEL}id$$filelist.level${level}.gz" \
        && rm -f "$logpath/${LABEL}id$$filelistNOT-OK.level$level"


mv "$logpath/${LABEL}id$$starttimeNOT-OK.level$level" \
	"$logpath/${LABEL}id$$starttime.level$level"
}
###################end of BACKMEUP ###########################





######################## START ##############################
START ()
{
echo -e \\n "($(date) secbak version 1.7"

case  $level in
  0)	# If it is a level 0 dump simply dump everything...

	######### begin of uncomment one example only /////


	### archive compressed files on a non rewinding tape
	#BACKMEUP "afio -ovz -Z /dev/nst0" 

	### archive PGP-encrypted compressed files on a non rewinding tape
	###   open a second input stream for PGP
	###   pgp needs a tmp directory which should only be readable for root
	#export TMP=/root/bin/secbak.tmpdir 
	#export PGPPASSFD=3 
	#export RANDSEED=~/.pgp/randseed.bin
	#passphrasefile=$TMP/secbak.parms
 	#BACKMEUP "afio -ovz -Z -U -P pgp -Q -fc -Q +verbose=0 
	#		     -3 3
	#             /dev/nst0" \
	#		3<$passphrasefile 



	### archive Gnu-PG encrypted compressed files on a non rewinding tape
	###   open a second input stream for GnuPg
	#passphrasefile=/root/bin/secbak.tmpdir/secbak.parms
 	#BACKMEUP "afio -ovz -Z -U -P gpg -Q --symmetric 
	#	     -Q --passphrase-fd=3 -Q --no-verbose 
	#	     -Q --batch -Q --no-options -3 3
	#             /dev/nst0" \
	#		3<$passphrasefile




	###archive compressed files directly on a HD floppy
	###as a multi-volume archive
 	BACKMEUP "afio -ovz -s1440k -Z /dev/fd0" 


	###archive pgp-encrypted compressed files directly on a HD floppy
	###as multi-volume archive
	###   open a second input stream for pgp
	###   pgp needs a tmp directory which should only be readable for root
	#export TMP=/root/bin/secbak.tmpdir 
	#export PGPPASSFD=3 
	#export RANDSEED=~/.pgp/randseed.bin
	#passphrasefile=$TMP/secbak.parms
 	#BACKMEUP "afio -ovz -s1440k -Z -U -P pgp -Q -fc -Q +verbose=0 
	#		     -3 3
	#             /dev/fd0" \
	#		3<$passphrasefile 

	###archive GnuPG-encrypted compressed files directly on a HD floppy
	###as multi-volume archive
	###   open a second input stream for GnuPg
	#passphrasefile=/root/bin/secbak.tmpdir/secbak.parms
 	#BACKMEUP "afio -ovz -s1440k -Z -U -P gpg -Q --symmetric 
	#	     -Q --passphrase-fd=3 -Q --no-verbose 
	#	     -Q --batch -Q --no-options -3 3
	#             /dev/fd0" \
	#		3<$passphrasefile

	######### end of uncomment one example only /////
	;;


  [1-9]) 
	### Otherwise dump only stuff newer...


	########## begin of uncomment one example only /////

	### archive compressed files on a non rewinding tape
	#BACKMEUP "afio -ovz -Z /dev/nst0" 




	### archiv PGP compressed encrypted files on a non rewinding tape
	### open a second input stream for PGP
	### pgp needs a tmp directory which should only be readable for root
	#export TMP=/root/bin/secbak.tmpdir 
	#export PGPPASSFD=3 
	#export RANDSEED=~/.pgp/randseed.bin
	#passphrasefile=$TMP/secbak.parms
 	#BACKMEUP "afio -ovz -Z -U -P pgp -Q -fc -Q +verbose=0 
	#	     -3 3
	#            /dev/nst0" \
	#		3<$passphrasefile 


	### archiv Gnu-PG compressed encrypted files on a non rewinding tape
	#export RANDSEED=~/.pgp/randseed.bin
	#passphrasefile=/root/bin/secbak.tmpdir/secbak.parms
 	#BACKMEUP "afio -ovz -Z -U -P gpg -Q --symmetric 
	#	     -Q --passphrase-fd=3 -Q --no-verbose 
	#	     -Q --batch -Q --no-options -3 3
	#            /dev/nst0" \
	#		3<$passphrasefile




	### archiv compressed files in file on a floppy	
	mount /floppy 
 	BACKMEUP "afio -ovz -s1440k -Z 
	             /floppy/${LABEL}id$$afioarchive.level$level" 
	umount /floppy




	### archive PGP- encrypted compressed files in file on floppy	
	###   open a second input stream for PGP
	###   pgp needs a tmp directory which should only be readable for root
	#mount /floppy 
	#export TMP=/root/bin/secbak.tmpdir 
	#export PGPPASSFD=3 
	#export RANDSEED=~/.pgp/randseed.bin
	#passphrasefile=$TMP/secbak.parms
 	#BACKMEUP "afio -ovz -s1440k -Z -U -P pgp -Q -fc -Q +verbose=0 
	#	     -3 3
	#             /floppy/${LABEL}id$$afioarchiv.level$level" \
	#		3<$passphrasefile 
	#umount /floppy



	### archive Gnupg encrypted compressed files in file on floppy	
	###   open a second input stream for GnuPG 
	#mount /floppy 
	#passphrasefile=/root/bin/secbak.tmpdir/secbak.parms
 	#BACKMEUP "afio -ovz -s1440k -Z -U -P gpg -Q --symmetric 
	#	     -Q --passphrase-fd=3 -Q --no-verbose 
	#	     -Q --batch -Q --no-options -3 3
	#             /floppy/${LABEL}id$$afioarchiv.level$level" \
	#		3<$passphrasefile
	#umount /floppy




	########## end of uncomment one example only /////





	;;

  *)	# print short help
	$0 
	echo ')' 
	exit 1
	;;
esac
echo ')' 
}
###############end of START #############################







############## MAIN #####################################
# There is probably no need to change anything in this function

level=$1
LABEL=$2



test  -d $logpath ||
  if ! mkdir --parents $logpath
  then
    echo "ABORT!"
    echo -e "\t Can\'t mkdir $logpath to store the logfiles."
    echo -e "\t Please start this script as root or modify the \$logpath"
    echo -e "\t definition there." 
    exit 1
  fi



# log all output in ...
START 2>&1 | tee --append "$logpath/backuphistory.txt"
############## end of MAIN #######################

