File: automatic_backup

package info (click to toggle)
dar 2.8.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 12,024 kB
  • sloc: cpp: 86,219; sh: 6,978; ansic: 895; makefile: 489; python: 242; csh: 115; perl: 43; sed: 16
file content (994 lines) | stat: -rw-r--r-- 32,332 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
#Written by Manuel Iglesias. glesialo@tiscali.es
#Notes:
SystemDirectory=/sbin
# This file should be copied (by CopySystemFiles) to its corresponding Directory (see above).
# Exit codes at the end of this file.

CommandName=`basename $0`



#########################################################
# BACKUP SETUP. BEGIN. Read Dar Doc before modification.
#########################################################
# Permissions.
##################
# Allow use only in run level 1.
CheckRunLevel=false
#
# Allow use only by root (Super user).
CheckUser=true
#
#########################################################
# Paths and files.
##################
# Directories.
#########
# Backup files Directory: Absolute path (Should start with '/'!!). Don't end it with '/' unless it is '/'.
DestinationDir=/store/.Store/Backup
#
# Origin of Backup/Restore Directory: Absolute path (Should start with '/'!!).
# Don't end it with '/' unless it is '/'.
OriginDir=/
#
# Directories to backup. Relative to Origin of Backup Dir! Empty means: all dirs
# (Except those in Directories to ignore. See below.). Separate with spaces.
SubDirsToBackup="root home"
#
# Directories to ignore. Relative to Origin of Backup Dir! Separate with spaces.
SubDirsToIgnore="home/manolo2 home/manolo/documents/Secret */.Trash* .Trash*\
 */.mozilla/*/[Cc]ache */.opera/[Cc]ache* */.pan/*/[Cc]ache */.thumbnails"
#
# DestinationDir will be automatically included in SubDirsToIgnore if DestinationDir is a subdirectory
# of OriginDir. If you want to include the base (IE.: Temp if DestinationDir: OriginDir/Temp/Backup) of
# DestinationDir instead, set constant IgnoreBaseOfDestinationDir to true. Value (true | false).
IgnoreBaseOfDestinationDir=true
#
# File systems that should be mounted for a correct backup. If any of them has to be mounted,
# it will be umounted before this shellscript exits. Please mind mounting order!!
# Absolute path (Should start with '/'!!). Separate with spaces.
DirsToMount="/home /home/common /store"
#
##################
# Files.
#########
# Files to backup. Empty: all files (Except those in Files to ignore. See below.).
# No Path. Separate with spaces.
FilesToBackup=""
#
# Files that should not be included in backup. No Path. Separate with spaces.
FilesToIgnore="*~ .*~ cryptfile0.crypt cryptfile1.crypt"
#
# Files that should not to be compressed. No Path. Separate with spaces.
FilesNotToCompress="*.dar *.crypt *.arj *.bz2 *.bz *.zst *.Z *.tgz *.taz *.cpio *.deb\
 *.gtar *.gz *.lzh *.lhz *.rar *.rpm *.shar *.sv4cpi *.sv4crc *.tar *.ustar *.zoo\
 *.zip *.jar *.jpg *.gif *.mpg *.mpeg *.avi *.ram *.rm"
#
#########################################################
# Parameters used to choose Differential Backup level.
##################
BlockSize=1024
#
# When Diffbackup > (MaxDiffPercentOfFullBackup% of FullBackup): New FullBackup recommended.
MaxDiffPercentOfFullBackup=30
#
# When Diffbackup < (MinDiffPercentOfFullBackup% of FullBackup): Rewrite first DiffBackup recommended.
MinDiffPercentOfFullBackup=3
#
# Max 99. If (Nr of DiffBackups) > MaxNrOfDiffBackups: Rewrite first DiffBackup recommended.
MaxNrOfDiffBackups=20
#
#########################################################
# Dar settings and options.
##################
#Used dar suite program names.
DarManagerName=dar_manager
DarName=dar
#
# Directory where dar usually resides. Absolute path (Should start with '/'!!). Don't end it with '/'.
DarDir=/usr/local/bin
#
# Create empty sub-directories in backup instead of those not saved. Value (true | false).
BackupIgnoredDirsEmpty=true
#
# CompressWithBZip2=false -> no compression. Value (true | false).
CompressWithBZip2=true
#
# Compress Files > 100Mb. Only valid if CompressWithBZip2=true. Value (true | false).
CompressBigFiles=true
#
# Value (true | false).
VerboseMode=false
#
# Value (true | false).
MakeSlices=true
#
# StopAfterSlices: Only valid if MakeSlices=true. Value (true | false).
StopAfterSlices=false
#
# SizeOfDarStatic: dar_static + DocFiles + Restore shell + etc (To calculate first slize size).
SizeOfDarStatic=4
#
SliceSize=650
#
#########################################################
# BACKUP SETUP. END.  Read Dar Doc before modification.
#########################################################



#########################################################
# SUBROUTINES. BEGIN.
#########################################################

echoE()
{
# echo to standard error. Remove leading/trailing blanks and double spaces.
echo $* 1>&2
	return 0
}

Usage()
{
echoE "$CommandName creates (Using '$DarName'), in directory"
echoE "'$DestinationDir',"
echoE "a backup of all files and directories in"
echoE "'$OriginDir'."
echoE "It analyzes current backup files and recommends the most suitable new"
echoE "backup level to the user. It also creates/updates a database with backup"
echoE "information for future Backup management (Using '$DarManagerName')."
echoE
echoE "The backup will be split in files of $SliceSize Mb to fit in removable media."
echoE
echoE "Usage: $CommandName. (User can choose backup level)."
echoE "or"
echoE "Usage: $CommandName -auto. ($CommandName selects backup level automatically)."
echoE
	return 0
}

UmountDirs ()
{
if [ "$DirsToUMount" != "" ]
  then
    echo "############"
    echo "$CommandName: Unmounting file systems:"
    for i in $DirsToUMount
      do
        mount | grep -w $i &> /dev/null
        if [ $? -eq 0 ]
          then
            if (umount $i &> /dev/null)
              then
                echo "$CommandName: $i unmounted."
              else
                echoE "$CommandName: $i could not be unmounted."
            fi
          else
            echo "$CommandName: $i was already unmounted."
        fi
      done
fi
echo "############"
	return 0
}

TwoDigits ()
{
#Add leftmost 0
if [ $1 -lt 10 ]
  then
    echo 0$1
  else
    echo $1
fi
	return 0
}

Stream()
{
# Output String(s) without letting the Shell interpret metacharacters.
# Remove leading/trailing blanks and double spaces.
# Enclose arguments in "" when calling. I.E.: Stream "$Var1 $Var2"
TempStr=$@
Length=${#TempStr}
  if [ $Length -eq 0 ]
    then
      return
    else
      CharNum=0
      while [ $CharNum -lt $Length ]
        do
          echo -n "${TempStr:$CharNum:1}"
          let CharNum++
        done
      echo
  fi
return
}

#########################################################
# SUBROUTINES. END.
#########################################################



NoUserChoice=false
if [ $# -ne 0 ]
  then
    if [ "$1" == "-auto" ]
      then
        NoUserChoice=true
      else
        Usage
        exit 1
    fi
fi

if $CheckRunLevel
  then
    RunLevel=`runlevel | sed 's/.* //'`
    if [ $RunLevel != S ]
      then
        echoE "$CommandName: RunLevel: $RunLevel. Please change to RunLevel 1 (init 1) and try again."
        exit 1
    fi
fi

if $CheckUser
  then
    CurrentUser=`whoami`
    if [ "$CurrentUser" != "root" ]
      then
        echoE "$CommandName: User: '$CurrentUser'. Please login as 'root' and try again."
        exit 1
    fi
fi
echo "############"

DirsToUMount=""
if [ "$DirsToMount" != "" ]
  then
    echo "$CommandName: Mounting file systems:"
    for i in $DirsToMount
      do
        mount | grep -w $i &> /dev/null
        if [ $? -ne 0 ]
          then
            if (mount $i &> /dev/null)
              then
                echo "$CommandName: $i mounted."
                DirsToUMount=" $i"$DirsToUMount
              else
                echoE "$CommandName: $i could not be mounted. Aborting."
                UmountDirs
                exit 2
            fi
          else
            echo "$CommandName: $i was already mounted."
        fi
      done
    echo "############"
fi

if [ "$OriginDir" != "/" ]
  then
#   if first character is not '/'.
    if [ "${OriginDir:0:1}" != "/" ]
      then
        echoE "$CommandName: 'Origin' directory:"
        echoE "$CommandName: $OriginDir."
        echoE "$CommandName: Must be an absolute path (Should start with '/'!)."
        echoE "$CommandName: Please edit '$CommandName' and try again."
        UmountDirs
        exit 3
      else
#       if last character is '/'.
        if [ "${OriginDir:${#OriginDir}-1:1}" == "/" ]
          then
            echoE "$CommandName: 'Origin' directory:"
            echoE "$CommandName: $OriginDir."
            echoE "$CommandName: Should not end with '/'!."
            echoE "$CommandName: Please edit '$CommandName' and try again."
            UmountDirs
            exit 3
          else
            if test ! -d $OriginDir
              then
                echoE "$CommandName: 'Origin' directory:"
                echoE "$CommandName: $OriginDir."
                echoE "$CommandName: Does not exist. Please edit '$CommandName' and try again."
                UmountDirs
                exit 3
            fi
        fi
    fi
fi

if [ "$DestinationDir" != "/" ]
  then
#   if first character is not '/'.
    if [ "${DestinationDir:0:1}" != "/" ]
      then
        echoE "$CommandName: 'DestinationDir' directory:"
        echoE "$CommandName: $DestinationDir."
        echoE "$CommandName: Must be an absolute path (Should start with '/'!)."
        echoE "$CommandName: Please edit '$CommandName' and try again."
        UmountDirs
        exit 3
      else
#       if last character is '/'.
        if [ "${DestinationDir:${#DestinationDir}-1:1}" == "/" ]
          then
            echoE "$CommandName: 'DestinationDir' directory:"
            echoE "$CommandName: $DestinationDir."
            echoE "$CommandName: Should not end with '/'!."
            echoE "$CommandName: Please edit '$CommandName' and try again."
            UmountDirs
            exit 3
          else
            if test ! -d $DestinationDir
              then
                echoE "$CommandName: 'DestinationDir' directory:"
                echoE "$CommandName: $DestinationDir."
                echoE "$CommandName: Does not exist. Please edit '$CommandName' and try again."
                UmountDirs
                exit 3
            fi
        fi
    fi
fi

if [ $OriginDir == $DestinationDir ]
  then
    echoE "$CommandName: 'DestinationDir' and 'OriginDir' can not be the same directory!"
    echoE "$CommandName: Please edit '$CommandName' and try again."
    UmountDirs
    exit 3
fi

# Find dar & dar_manager
if type >/dev/null 2>&1 $DarName
  then
    DarFound=true
  else
    DarFound=false
fi
if type >/dev/null 2>&1 $DarManagerName
  then
    DarManagerFound=true
  else
    DarManagerFound=false
fi
if ! ($DarFound && $DarManagerFound)
  then
    if [ "$DarDir" != "/" ]
      then
#       if first character is not '/'.
        if [ "${DarDir:0:1}" != "/" ]
          then
            echoE "$CommandName: 'DarDir' directory:"
            echoE "$CommandName: $DarDir."
            echoE "$CommandName: Must be an absolute path (Should start with '/'!)."
            echoE "$CommandName: Please edit '$CommandName' and try again."
            UmountDirs
            exit 3
          else
#           if last character is '/'.
            if [ "${DarDir:${#DarDir}-1:1}" == "/" ]
              then
                echoE "$CommandName: 'DarDir' directory:"
                echoE "$CommandName: $DarDir."
                echoE "$CommandName: Should not end with '/'!."
                echoE "$CommandName: Please edit '$CommandName' and try again."
                UmountDirs
                exit 3
              else
                if test ! -d $DarDir
                  then
                    echoE "$CommandName: 'DarDir' directory:"
                    echoE "$CommandName: $DarDir."
                    echoE "$CommandName: Does not exist. Please edit '$CommandName' and try again."
                    UmountDirs
                    exit 3
                fi
            fi
        fi
    fi
#   Include directory, where dar usually resides, in PATH."
#   DarDir not in PATH?
    echo $PATH | grep $DarDir &> /dev/null
    if [ $? -ne 0 ]
      then
        PATH=$DarDir":"$PATH
    fi
fi
if ! type >/dev/null 2>&1 $DarName
  then
    echoE "$CommandName: $DarName neither in PATH nor in $DarDir. Aborting."
    UmountDirs
    exit 3
fi
if ! type >/dev/null 2>&1 $DarManagerName
  then
    echoE "$CommandName: $DarManagerName neither in PATH nor in $DarDir. Aborting."
    UmountDirs
    exit 3
fi

#########################################################
# VARIABLES INITIALIZATION. BEGIN.
#########################################################
# Backup Paths.
###############
#Backup base names & DataBase name.
FullBackupBaseName=$CommandName"Full"
DiffBackupBaseName=$CommandName"Diff"
DataBaseName=$CommandName"DataBase"
#
FullBackupPath=$DestinationDir/$FullBackupBaseName
DiffBackupPath=$DestinationDir/$DiffBackupBaseName
DataBasePath=$DestinationDir/$DataBaseName
#
#########################################################
# Set dar options.
###############
# Backup base name (Will be set later): -c PathBackUpBaseName
BackupNameOption="-c "
#
# Reference backup (Will be set later) for differential backups: -A PathBackUpBaseName
ReferenceBackupOption="-A "
#
# Origin of Backup: -R /.
DarOptions="-R "$OriginDir
#
# Compress data inside the backup using bzip2: -y[CompressLevel].
# CompressLevel: 0 minimum; 9 maximun. Compress Files > 100Mb: -m 0.
if $CompressWithBZip2
  then
    DarOptions=$DarOptions" -y9"
    if $CompressBigFiles
      then
        DarOptions=$DarOptions" -m 0"
    fi
fi
#
# Verbose mode: -v
if $VerboseMode
  then
    DarOptions=$DarOptions" -v"
fi
#
# Create empty sub-directories in backup instead of those not saved: -D
if $BackupIgnoredDirsEmpty
  then
    DarOptions=$DarOptions" -D"
fi
#
# Do not read ~/.darrc nor /etc/darrc configuration file: -N
DarOptions=$DarOptions" -N"
#
#########################################################
#Set Slice options.
###############
if [ $SliceSize -gt $SizeOfDarStatic ]
  then
    let FirstSliceSize=$SliceSize-$SizeOfDarStatic
  else
    FirstSliceSize=$SliceSize
fi
#
# All sizes in Mb; Stop after each slize.
if $MakeSlices
  then
    FirstSliceSizeOption="-S "$FirstSliceSize"M"
    SliceSizeOption="-s "$SliceSize"M"
#   Pause between slices to change removable media. Ring bell: -p -b
    if $StopAfterSlices
      then
        DarOptions=$DarOptions" -p -b"
    fi
  else
    FirstSliceSizeOption=""
    SliceSizeOption=""
fi
#
#########################################################
#Set Include/Exclude Files Options.
###############
# Files you don't want to backup: -X "*~" -X ".*~"
if [ "$FilesToIgnore" != "" ]
  then
    InclExclFilesOption='-X "'`Stream "$FilesToIgnore" |  sed 's/ /" -X "/g'`'"'
  else
    InclExclFilesOption=""
fi
#
# Files you want to backup without compression: -Z "*.zip"
if $CompressWithBZip2
  then
    if [ "$FilesNotToCompress" != "" ]
      then
        InclExclFilesOption=$InclExclFilesOption' -Z "'`Stream "$FilesNotToCompress" |  sed 's/ /" -Z "/g'`'"'
    fi
fi
#
#  Files to include in backup: -I "*.html".
if [ "$FilesToBackup" != "" ]
  then
    InclExclFilesOption=' -I "'`Stream "$FilesToBackup" |  sed 's/ /" -I "/g'`'" '$InclExclFilesOption
fi
#
#########################################################
#Set Include/Exclude directories Options.
###############
# $OriginDir in $DestinationDir?
echo $DestinationDir | grep $OriginDir &> /dev/null
if [ $? -eq 0 ]
  then
#   TempDir= $DestinationDir-$OriginDir
    TempDir=`echo $DestinationDir | sed s%$OriginDir%%`
    if $IgnoreBaseOfDestinationDir
      then
#       Include BaseDir of DestinationDir (Without first '/') in SubDirsToIgnore.
#       if first character, in TempDir, is not '/'.
        if [ "${DestinationDir:0:1}" != "/" ]
          then
#           Add '/' in front.
            TempDir="/"$TempDir
        fi
        TempPath=$TempDir
        while [ $TempPath != `dirname $TempPath` ]
          do
            BasePath=$TempPath
            TempPath=`dirname $TempPath`
          done
        BasePath=`basename $BasePath`
        if [ "$SubDirsToIgnore" != "" ]
          then
            SubDirsToIgnore=$SubDirsToIgnore" $BasePath"
          else
            SubDirsToIgnore=$BasePath
        fi
      else
#       Include DestinationDir (Without first '/') in SubDirsToIgnore.
#       if first character, in TempDir, is '/'.
        if [ "${TempDir:0:1}" == "/" ]
          then
#           Remove first '/'.
            TempDir=${TempDir:1:${#TempDir}-1}
        fi
        if [ "$SubDirsToIgnore" != "" ]
          then
            SubDirsToIgnore=$SubDirsToIgnore" $TempDir"
          else
            SubDirsToIgnore=$TempDir
        fi
    fi
fi
#
# Sub-trees you must not save: -P dev/pts -P proc. Path must be relative to -R option
# Enclose each directory in "" just in case there are metacharacters in the name.
if [ "$SubDirsToIgnore" != "" ]
  then
    IncludeExclDirsOption='-P "'`Stream "$SubDirsToIgnore" |  sed 's/ /" -P "/g'`'"'
  else
    IncludeExclDirsOption=""
fi
#
#  Sub-trees you must save: Add without any option in front.
# Enclose each directory in "" just in case there are metacharacters in the name.
if [ "$SubDirsToBackup" != "" ]
  then
    IncludeExclDirsOption='-g"'`Stream "$SubDirsToBackup" | sed 's/ /" -g "/g'`'" '$IncludeExclDirsOption
fi
#
#########################################################
# Set dar_manager options.
###############
# Create DataBase: -C PathBaseName
CreateDataBaseOption="-C "$DataBasePath
#
# DataBase used as reference: -B PathBaseName
DataBaseNameOption="-B "$DataBasePath
#
# Add Archive to DataBase (Will be set later): -A PathArchiveName
AddToDataBaseOption="-A "
#
#########################################################
# VARIABLES INITIALIZATION. END.
#########################################################



FullDiffBackupSize=`ls -1 -s --block-size=$BlockSize $FullBackupPath.* 2> /dev/null | awk '{s = s + $1}
                                                                                               END {print s}'`
if [ "$FullDiffBackupSize" == "" ]
  then
    FullDiffBackupSize=0
fi
TotalDiffBackupSize=`ls -1 -s --block-size=$BlockSize $DiffBackupPath??.* 2> /dev/null | awk '{s = s + $1}
                                                                                                  END {print s}'`
if [ "$TotalDiffBackupSize" == "" ]
  then
    TotalDiffBackupSize=0
fi

echo "$CommandName: ### `date --rfc-822` ###"
echo "$CommandName: Current backup information (Size in $BlockSize bytes blocks.):"
if [ $FullDiffBackupSize -eq 0 ]
  then
    echo "$CommandName: No $FullBackupBaseName files found!"
    echo "############"
    echo "$CommandName: Preparing to Create $FullBackupBaseName."
    DiffBackupNr=0
    LastDiffBackup=$DiffBackupNr
  else
    echo "$CommandName: ..$FullBackupBaseName: $FullDiffBackupSize."
    if [ $TotalDiffBackupSize -eq 0 ]
      then
        DiffBackupNr=1
        LastDiffBackup=0
        BaseName=$DiffBackupBaseName`TwoDigits $DiffBackupNr`
        echo "############"
        echo "$CommandName: Preparing to Create $BaseName."
      else
        echo "$CommandName: ..$DiffBackupBaseName: $TotalDiffBackupSize:"
        DiffBackupNr=0
        LastDiffBackup=$DiffBackupNr
        BestChoiceDiffLevel=""
        RemainingDiffSize=$TotalDiffBackupSize
        CurrentSize=1
        while [ $CurrentSize -ne 0 ]
          do
            let DiffBackupNr++
            BaseName=$DiffBackupPath`TwoDigits $DiffBackupNr`
            CurrentSize=`ls -1 -s --block-size=$BlockSize $BaseName.* 2> /dev/null | awk '{s = s + $1}
                                                                                         END {print s}'`
            if [ "$CurrentSize" == "" ]
             then
               CurrentSize=0
            fi
            if [ $CurrentSize -ne 0 ]
              then
                LastDiffBackup=$DiffBackupNr
                let RemainingDiffSize=$RemainingDiffSize-$CurrentSize
                if [ "$BestChoiceDiffLevel" == "" ] && [ $CurrentSize -lt $RemainingDiffSize ]
                  then
                    BestChoiceDiffLevel=$DiffBackupNr
                fi
                BaseName=$DiffBackupBaseName`TwoDigits $DiffBackupNr`
                echo "$CommandName: ....$BaseName: $CurrentSize."
            fi
          done
        echo "############"
        let NextDiffBackup=$LastDiffBackup+1
        if [ "$BestChoiceDiffLevel" == "" ]
          then
            BestChoiceDiffLevel=$NextDiffBackup
        fi
         Choice[4]="Exit $CommandName."
        let MinDiffBackupSize=$FullDiffBackupSize*$MinDiffPercentOfFullBackup/100
        if [ $TotalDiffBackupSize -lt $MinDiffBackupSize ]
          then
            BestChoiceDiffLevel=1
            Choice[1]=" ($DiffBackupBaseName<$MinDiffPercentOfFullBackup%$FullBackupBaseName)."
        fi
        if [ $LastDiffBackup -gt $MaxNrOfDiffBackups ]
          then
            BestChoiceDiffLevel=1
            Choice[1]=${Choice[1]}" (NrOfDiffBackups>$MaxNrOfDiffBackups)."
        fi
        BaseName=$DiffBackupBaseName`TwoDigits $BestChoiceDiffLevel`
        Choice[1]=" $BaseName."${Choice[1]}
        BaseName=$DiffBackupBaseName`TwoDigits $NextDiffBackup`
        Choice[2]="Create $BaseName. Faster."
        Choice[3]="Rewrite $FullBackupBaseName ($DiffBackupBaseName>$MaxDiffPercentOfFullBackup%$FullBackupBaseName). Recommended!"
        let MaxDiffBackupSize=$FullDiffBackupSize*$MaxDiffPercentOfFullBackup/100
        if [ $NextDiffBackup -eq $BestChoiceDiffLevel ]
          then
            if [ $TotalDiffBackupSize -gt $MaxDiffBackupSize ]
              then
                Choices="1 3"
                CreateRewriteMode="Create"
                Choice[1]=${Choice[1]}" Faster."
              else
                Choices=""
            fi
          else
            CreateRewriteMode="Rewrite"
            if [ $TotalDiffBackupSize -gt $MaxDiffBackupSize ]
              then
                Choices="1 2 3"
              else
                Choices="1 2"
                Choice[1]=${Choice[1]}" Recommended!"
            fi
        fi
        Choice[1]=$CreateRewriteMode${Choice[1]}
        if [ "$Choices" == "" ]
          then
            DiffBackupNr=$BestChoiceDiffLevel
            BaseName=$DiffBackupBaseName`TwoDigits $DiffBackupNr`
            echo "$CommandName: Preparing to Create $BaseName."
          else
            Choices=$Choices" 4"
            echo "$CommandName: Options:"
            ChoiceNr=1
            for i in $Choices
              do
                echo "$CommandName: $ChoiceNr.${Choice[$i]}"
                let ChoiceNr++
              done
            echo "############"
            if $NoUserChoice
              then
                echo $Choices | grep "3" &> /dev/null
                if [ $? -eq 0 ]
                  then
                    Choice=3
                  else
                    Choice=1
                fi
              else
                let ChoiceNr--
                ValidNumber=false
                until $ValidNumber
                  do
                    read -p "$CommandName: Please choose a number: " UserChoice
                    case $UserChoice in
                      [a-zA-Z-_.,]* | *[a-zA-Z-_.,] | *[a-zA-Z-_.,]*)
                        echoE "$CommandName: No alpha characters allowed. Please try again.";;
                      "") ;;
                      *)
                        ValidNumber=true;;
                    esac
                    if $ValidNumber
                     then
                       if [ $UserChoice -lt 1 ] || [ $UserChoice -gt $ChoiceNr ]
                         then
                           echoE "$CommandName: Allowed number range: 1..$ChoiceNr. Please try again."
                           ValidNumber=false
                       fi
                    fi
                  done
                ChoiceNr=0
                for i in $Choices
                  do
                    let ChoiceNr++
                    if [ $ChoiceNr -eq $UserChoice ]
                     then
                       Choice=$i
                    fi
                  done
                echo "############"
            fi
            case $Choice in
              1)
                DiffBackupNr=$BestChoiceDiffLevel
                BaseName=$DiffBackupBaseName`TwoDigits $DiffBackupNr`
                echo "$CommandName: Preparing to $CreateRewriteMode $BaseName.";;
              2)
                DiffBackupNr=$NextDiffBackup
                BaseName=$DiffBackupBaseName`TwoDigits $DiffBackupNr`
                echo "$CommandName: Preparing to Create $BaseName.";;
              3)
                echo "$CommandName: Preparing to Rewrite $FullBackupBaseName."
                DiffBackupNr=0;;
              4)
                echoE "$CommandName: Program exits at user request."
                UmountDirs
                exit 4;;
              *)
                echoE "$CommandName:Warning: Incorrect choice: $Choice. Aborting."
                UmountDirs
                exit 5;;
            esac
        fi
    fi
fi

if [ $DiffBackupNr -eq 0 ]
  then
    FullBackup=true
  else
    FullBackup=false
fi

if $FullBackup
  then
    BackupNameOption=$BackupNameOption$FullBackupPath
    if [ $FullDiffBackupSize -ne 0 ]
      then
        echo "############"
        echo "$CommandName: Removing previous $FullBackupBaseName files."
        for i in $FullBackupPath.*
          do
            if test -f $i
              then
                if (rm $i)
                  then
                    echo "$CommandName: $i removed."
                  else
                    echoE "$CommandName:Warning: Failure to remove $i."
                fi
            fi
          done
    fi
    if [ $TotalDiffBackupSize -ne 0 ]
      then
        echo "############"
        echo "$CommandName: Removing previous $DiffBackupBaseName files."
        for i in $DiffBackupPath??.*
          do
            if test -f $i
              then
                if (rm $i)
                  then
                    echo "$CommandName: $i removed."
                  else
                    echoE "$CommandName:Warning: Failure to remove $i."
                fi
            fi
          done
    fi
    if test -f $DataBasePath
      then
        echo "############"
        echo "$CommandName: Removing previous $DataBaseName file."
        if (rm $DataBasePath)
          then
            echo "$CommandName: $DataBasePath removed."
          else
            echoE "$CommandName:Warning: Failure to remove $DataBasePath."
        fi
    fi
    echo "############"
    echo "$CommandName: creating $FullBackupBaseName. Please wait."
    echo "###"
    sh <<End
    $DarName $FirstSliceSizeOption $SliceSizeOption $BackupNameOption $DarOptions $IncludeExclDirsOption $InclExclFilesOption
End
    ExitCode=$?
    if [ $ExitCode -eq 0 ]
      then
        echo "###"
        echo "$CommandName: $FullBackupBaseName created successfully."
        echo "############"
        echo "$CommandName: Creating $DataBaseName."
        AddToDataBaseOption=$AddToDataBaseOption$FullBackupPath
        if ($DarManagerName $CreateDataBaseOption)
          then
            echo "$CommandName: Adding $FullBackupBaseName to $DataBaseName. Please wait."
            if ($DarManagerName $DataBaseNameOption $AddToDataBaseOption)
              then
                echo "$CommandName: $FullBackupBaseName added to $DataBaseName successfully."
              else
                echoE "$CommandName: Warning: Adding $FullBackupBaseName to $DataBaseName failed."
            fi
          else
            echoE "$CommandName: Warning: Creation of $DataBaseName failed."
        fi
      else
        echoE "$CommandName: Sorry. '$DarName' failed with exit code $ExitCode. $FullBackupBaseName backup aborted."
        UmountDirs
    fi
  else
    BackupName=$DiffBackupBaseName`TwoDigits $DiffBackupNr`
    BackupPath=$DiffBackupPath`TwoDigits $DiffBackupNr`
    BackupNameOption=$BackupNameOption$BackupPath
    if [ $DiffBackupNr -gt 1 ]
      then
        PrevDiffBackup=$DiffBackupNr
        let PrevDiffBackup--
        ReferenceBackupOption=$ReferenceBackupOption$DiffBackupPath`TwoDigits $PrevDiffBackup`
      else
        ReferenceBackupOption=$ReferenceBackupOption$FullBackupPath
    fi
#   In fact $DiffBackupNr+1 because FullBackup=1. Set to $DiffBackupNr for use in 'Erase .. from DataBase' loop below.
    DataBaseLastValidArchive=$DiffBackupNr
    if [ $LastDiffBackup -ne 0 ]
      then
        if [ $DiffBackupNr -le $LastDiffBackup ]
          then
            echo "############"
            echo "$CommandName: Removing previous $DiffBackupBaseName files."
        fi
        let DiffBackupNr--
        while [ $DiffBackupNr -lt $LastDiffBackup ]
          do
            let DiffBackupNr++
            BaseName=$DiffBackupPath`TwoDigits $DiffBackupNr`
            for i in $BaseName.*
              do
                if test -f $i
                  then
                    if (rm $i)
                      then
                        echo "$CommandName: $i removed."
                      else
                        echoE "$CommandName:Warning: Failure to remove $i."
                    fi
                fi
              done
          done
    fi
    if test -f $DataBasePath
      then
#       $DarManagerName -l outputs to standard error.
        LastArchiveInDB=`$DarManagerName $DataBaseNameOption -l 2>&1 | awk 'END {print $1}'`
        case $LastArchiveInDB in
          [a-zA-Z-_.,]* | *[a-zA-Z-_.,] | *[a-zA-Z-_.,]*)
#           If DataBase empty last line produced by 'dar_manager -l' is full of '--'
            echoE "$CommandName: Warning: $DataBaseName is empty. Aborting."
            UmountDirs
            exit 6;;
          *)
            if [ $LastArchiveInDB -gt $DataBaseLastValidArchive ]
              then
                echo "############"
                echo "$CommandName: Erasing previous Differential backups from $DataBaseName."
                while [ $LastArchiveInDB -gt $DataBaseLastValidArchive ]
                  do
                    let ArchiveBaseName=$LastArchiveInDB-1
                    BaseName=`TwoDigits $ArchiveBaseName`
                    ArchiveBaseName=$DiffBackupBaseName$BaseName
                    if ($DarManagerName $DataBaseNameOption -D $LastArchiveInDB)
                      then
                        echo "$CommandName: Archive $LastArchiveInDB ($ArchiveBaseName) erased from $DataBaseName."
                      else
                        echoE "$CommandName: Warning: Erasing of Archive $LastArchiveInDB ($ArchiveBaseName)\
                                                                                  from $DataBaseName failed."
                    fi
                    let LastArchiveInDB--
                  done
            fi;;
        esac
      else
        echoE "$CommandName: Warning! $DataBaseName does not exist. Aborting."
        UmountDirs
        exit 7
    fi
    echo "############"
    echo "$CommandName: creating $BackupName. Please wait."
    echo "###"
    sh <<End
    $DarName $SliceSizeOption $BackupNameOption $ReferenceBackupOption $DarOptions $IncludeExclDirsOption $InclExclFilesOption
End
    ExitCode=$?
    if [ $ExitCode -eq 0 ]
      then
        echo "###"
        echo "$CommandName: $BackupName created successfully."
        echo "############"
        echo "$CommandName: Updating $DataBaseName. Please wait."
        AddToDataBaseOption=$AddToDataBaseOption$BackupPath
        if ($DarManagerName $DataBaseNameOption $AddToDataBaseOption)
          then
            echo "$CommandName: $BackupName added to $DataBaseName successfully."
          else
            echoE "$CommandName: Warning: Adding $BackupName to $DataBaseName failed."
        fi
      else
        echoE "$CommandName: Sorry. '$DarName' failed with exit code $ExitCode. $BackupName backup aborted."
    fi
fi

UmountDirs

exit 0

Exit codes:
0 Sucessful run.
1 Wrong arguments;
  || Not root;
  || Wrong runlevel.
2 File system could not be mounted.
3 Incorrect Origin directory or it does not exist;
  || Incorrect Destination directory or it does not exist;
  || $DarName or $DarManagerName not in $PATH or $DarDir.
4 User request exit.
5 Wrong user choice.
6 Database empty.
7 Database does not exist.