#!/bin/sh

#This is where all history files are stored /////
logpath=/var/adm/dump
mkdir --parents "$logpath"

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
#		: 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 may also use cpio to retore your
# archives. In this case it could 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 "secrest" 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. A revision by a bash programmer
# is also welcome.
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

# Version 1.7.1
# afios warnings result in a return status other than 0
# So we better grep again in afios messages for choosen 
# error messages in order to decide wether the backup 
# Was successfull or not.
 
# Version 1.7.2	
# Better use egrep instead of grep to grep in afiolog
#	12.10.1999				Jens Getreu

# Version 1.7.3
# Another example in START() added: backup on DVD using growisofs
# 	10.1.2004				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 \
#	/home/getreu/.vmware/ \
#        /root /root/bin -maxdepth 1 $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  /home/jens/Documents  /home/getreu/JENS_DATEN/DOKUMENTE/ \
     /home/getreu/Mail/ /home/jens/Mail \
     /home/getreu/.evolution/ \
     /home/getreu/.icedove/ \
     /home/getreu/.mozilla/iceowl/ \
     /home/getreu/BILDER/ \
     /home/jens/Documents/ \
     /usr/local/bak \
     ! -name "*level?.cpio" -and ! -path "tmp*"  \
	   $findadd  -print 
 find /home/getreu/JENS_DATEN /home/jens /home/getreu -maxdepth 1 -type f $findadd -print ) \
   |egrep -v '/Sicherungskopie|~$|/~|\$$|\.bak$|\.db$|\.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  "\t $prevdump"

	echo "Warning this version of $0 backups in incremental mode only files smaler then 1MB" 
	findadd="-cnewer $prevdump -size 1M"
        # choose this to do incremental backup of all files
	#findadd="-cnewer $prevdump"
        # do incremental backups only of small files 
	;;
esac

PREFIX="$logpath/$STARTTIME-$$-${LABEL}-"
SUFFIX=.level${level}


echo "Writing filelist in:" 
echo  "\t ${PREFIX}filelistNOT-OK${SUFFIX}" 
echo "and afios (error)  messages in:" 
echo  "\t ${PREFIX}afiologNOT-OK${SUFFIX}" 

#save startime in timestamp of file
echo $@ > "${PREFIX}starttimeNOT-OK${SUFFIX}"

echo "Starting Backup ..."
echo \"$@\"



error=false
CHOOSEFILES |tee "${PREFIX}filelistNOT-OK${SUFFIX}" \
	|nice --adjustment=-10 "$@" \
	1>>"${PREFIX}afiologNOT-OK${SUFFIX}" \
	2>&1 


#be sure having set afios "-1 a" option :
error=$? 

 
##Don't refer to afios exit status because it considers also warnings as errors
##So better grep in it's error messages. 
##Version 1.7.1 : this is not true any more

##if egrep '^afio:.*No|^afio:.*error|^afio:.*Aborted|^afio:.*buisy' \
##	"${PREFIX}afiologNOT-OK${SUFFIX}" \
##	|egrep -qv '^afio:.*No such file'
##	then error=true
##	else error=false
##fi

if [ $error != '0' ] 
	then 	echo '***ERRORs occurred!' \
		      'Your backup was probably NOT successfull***'
	     	echo "afios last 5 messages:"
		grep '^afio:' "${PREFIX}afiologNOT-OK${SUFFIX}" \
			| tail --lines 5
                echo "afios returncode was = $error"
		echo ')' 
		exit 1
	else 	echo "... Backup finished"
		echo "Here are afios messages:"
		grep '^afio:' "${PREFIX}afiologNOT-OK${SUFFIX}"
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  "compressing\t afiologNOT-OK${SUFFIX}"\
	"\t into: afiolog${SUFFIX}.gz"
echo  "\t and \t filelistNOT-OK${SUFFIX}"\
	"\t into: filelist${SUFFIX}.gz"

gzip -c "${PREFIX}afiologNOT-OK${SUFFIX}" \
	> "${PREFIX}afiolog${SUFFIX}.gz" \
	&& rm -f "${PREFIX}afiologNOT-OK${SUFFIX}"

gzip -c "${PREFIX}filelistNOT-OK${SUFFIX}" \
	> "${PREFIX}filelist${SUFFIX}.gz" \
        && rm -f "${PREFIX}filelistNOT-OK${SUFFIX}"

mv "${PREFIX}starttimeNOT-OK${SUFFIX}" \
	"${PREFIX}starttime${SUFFIX}"
}
###################end of BACKMEUP ###########################





######################## START ##############################
START ()
{
echo -e \\n "($(date) secbak version 1.8.0"
STARTTIME=$(date +%Y%m%d%H%M%S)

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 -h -ovz -Z -1 a /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 -h -ovz -Z -1 a -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 -h -ovz -Z -1 a -U -P gpg -Q --symmetric \
	#	     -Q --passphrase-fd=3 -Q --no-verbose \ 
	#	     -Q --batch -Q --no-options -3 3 \
	#             /dev/nst0 \
	#		3<$passphrasefile


	### Create  an  archive  on recordable CDs using the crdrecord
	#BACKMEUP afio -z -o -Z -b 2048 -s325000x \
	#	'!cdrecord -eject -v speed=24 dev=0,0,0 blank=fast -'        


	### Create  an  archive  on recordable DVD RW using the growisofs
	### a DVD can  contain about 4.377 GB or 4482 MB (or 4699717632 Bytes)
        ### a sector has 2048 Bytes
        ### so there is place for 2294784 sectors
	### The resulting afio-file can not be bigger than 200 less sectors
	### This is 2294584

	#/usr/bin/dvd+rw-format  -force /dev/sr0 
	#eject /dev/dvd0
	#eject -t /dev/dvd
	BACKMEUP afio -z -Z -b 2048 -s 2090000x -oxv \
		"! growisofs -stream-media-size 2090400 -Z /dev/sr0"

	### some uses growisofs like this but it doesn't work for me
        #find /directorio -depth -print0 | afio -oxv0 \
        #"! growisofs -use-the-force-luke -dvd-compat \
        #-Z /dev/hdd=/proc/self/fd/0" 

        ### Dummy
        #BACKMEUP cat - >&0

 
	###archive compressed files directly on a HD floppy
	###as a multi-volume archive
 	#BACKMEUP afio -h -ovz -s1440k -1 a -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 -h -ovz -s1440k -Z -1 a -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 -h -ovz -s1440k -1 a -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 -h -ovz -Z -1 a /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 -h -ovz -1 a -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 -h -ovz -Z -1 a -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 -h -1 a -ovz -s1440k -Z \
	#             /floppy/${LABEL}id$$afioarchiv.level$level 
	#umount /floppy



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




	### 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 echo afio -h -1 a -ovz -s1440k -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 -h -1 a -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


	### archiv compressed files in file on hd	
	#
	DESTDIR=/usr/local/bak/afioarchive.tmp 
	mkdir -p $DESTDIR
 	BACKMEUP afio -1 a -ovz -Z \
	             $DESTDIR/$STARTTIME-$$-${LABEL}${afioarchive}-level$level.cpio 
	chmod 600 $DESTDIR/$STARTTIME-$$-${LABEL}${afioarchive}-level$level.cpio 
	chown getreu:nogroup $DESTDIR/$STARTTIME-$$-${LABEL}${afioarchive}-level$level.cpio 
	########## 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 #######################
