This repository has been archived by the owner on Dec 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
star.sh
executable file
·2172 lines (1957 loc) · 85.2 KB
/
star.sh
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
995
996
997
998
999
1000
#!/bin/bash
# Set program version
BRversion="System Tar & Restore 7.0"
# Set EFI detection directory
BRefidir="/sys/firmware/efi"
# Delete temporary files if exist
clean_tmp_files() {
if [ -f /tmp/filelist ]; then rm /tmp/filelist; fi
if [ -f /tmp/error ]; then rm /tmp/error; fi
if [ -f /target_architecture.$(uname -m) ]; then rm /target_architecture.$(uname -m); fi
if [ -f /mnt/target/target_architecture.$(uname -m) ]; then rm /mnt/target/target_architecture.$(uname -m); fi
if [ -f "$BRmaxsize"/downloaded_backup ]; then rm "$BRmaxsize"/downloaded_backup; fi
}
# Calculate percentage and compose a simple progress bar
pstr="========================"
dstr="------------------------"
lastper="-1"
pgrs_bar() {
while read ln; do
x="$((x + 1))"
per="$((x*100/total))"
# If -v is given print percentage and full output
if [ -n "$BRverb" ] && [[ "$per" -le "100" ]]; then
echo -e "${CYAN}[$x / $total] ${YELLOW}[$per%] ${GREEN}$ln${NORM}"
elif [[ "$per" -gt "$lastper" ]] && [[ "$per" -le "100" ]]; then
lastper="$per"
print_msg "$mode_job: $per% ($x / $total Files)" 0
# The main progress bar
echo -ne "\r$mode_job: [${pstr:0:$((x*24/total))}${dstr:0:24-$((x*24/total))}] $per%"
fi
done
}
# Print various messages and update the gui wrapper
print_msg() {
if [ ! "$2" = "0" ]; then echo -e ${1}; fi
if [ -n "$BRwrtl" ]; then echo ${1#*'\n'} > /tmp/wr_proc; fi # also ignore leading newlines if any
}
# Print various error messages and exit
print_err() {
echo -e ${1} >&2
if [ "$2" = "0" ]; then exit; fi
if [ "$2" = "1" ]; then clean_unmount; fi
}
# Set the configuration file for Backup mode. If called from the wrapper don't source, the gui wrapper will source it
if [ -f "$1" ] && [ -z "$BRwrtl" ]; then
BRconf="$1"
elif [ -f /etc/backup.conf ] && [ -z "$BRwrtl" ]; then
BRconf="/etc/backup.conf"
fi
# Show version
echo "$BRversion"
# Set arguments and help page
BRargs="$(getopt -o "i:d:n:c:u:H:jqvgDP:E:oa:M:r:e:l:s:b:h:G:S:f:y:p:R:m:k:t:B:WFLT:" -l "mode:,destination:,filename:,compression:,user-opts:,home-dir:,no-color,quiet,verbose,generate,use-genkernel,passphrase:,encryption:,override,clean:,mc-threads:,root:,esp:,esp-mpoint:,swap:,boot:,home:,grub:,syslinux:,file:,username:,password:,rootsubvol:,mount-opts:,kernel-opts:,other-parts:,other-subvols:,ignore-efi,efistub,bootctl,src-dir:,help" -n "$1" -- "$@")"
if [ "$?" -ne "0" ]; then
echo "See star.sh --help"
exit
fi
eval set -- "$BRargs";
while true; do
case "$1" in
-i|--mode)
BRmode="$2"
# Source configuration file in Backup mode early so arguments can override it
if [ -f "$BRconf" ] && [ "$BRmode" = "0" ]; then
source "$BRconf"
fi
shift 2
;;
-u|--user-opts)
BRuseropts="$2"
shift 2
;;
-d|--destination)
BRdestination="$2"
shift 2
;;
-n|--filename)
BRname="$2"
shift 2
;;
-c|--compression)
BRcompression="$2"
shift 2
;;
-H|--home-dir)
BRhomedir="$2"
shift 2
;;
-P|--passphrase)
BRencpass="$2"
shift 2
;;
-E|--encryption)
BRencmethod="$2"
shift 2
;;
-T|--src-dir)
BRsrc="$2"
shift 2
;;
-j|--no-color)
BRnocolor="y"
shift
;;
-q|--quiet)
BRquiet="y"
shift
;;
-v|--verbose)
BRverb="y"
shift
;;
-g|--generate)
BRgen="y"
shift
;;
-D|--use-genkernel)
BRgenkernel="y"
shift
;;
-o|--override)
BRoverride="y"
shift
;;
-a|--clean)
BRclean="$2"
shift 2
;;
-M|--mc-threads)
BRmcthreads="$2"
shift 2
;;
-r|--root)
BRroot="$2"
shift 2
;;
-e|--esp)
BResp="$2"
shift 2
;;
-l|--esp-mpoint)
BRespmpoint="$2"
shift 2
;;
-s|--swap)
BRswap="$2"
shift 2
;;
-b|--boot)
BRboot="$2"
shift 2
;;
-h|--home)
BRhome="$2"
shift 2
;;
-G|--grub)
BRgrub="$2"
shift 2
;;
-S|--syslinux)
BRsyslinux="$2"
shift 2
;;
-f|--file)
BRuri="$2"
shift 2
;;
-y|--username)
BRusername="$2"
shift 2
;;
-p|--password)
BRpassword="$2"
shift 2
;;
-R|--rootsubvol)
BRrootsubvol="$2"
shift 2
;;
-m|--mount-opts)
BRmountopts="$2"
shift 2
;;
-k|--kernel-opts)
BRkernopts="$2"
shift 2
;;
-t|--other-parts)
BRparts=($2)
shift 2
;;
-B|--other-subvols)
BRsubvols=($2)
shift 2
;;
-W|--ignore-efi)
unset BRefidir
shift
;;
-F|--efistub)
BRefistub="y"
shift
;;
-L|--bootctl)
BRbootctl="y"
shift
;;
--help)
echo "Usage: star.sh [backup.conf] -i mode [options]
General Options:
-i, --mode Select mode: 0 (Backup) 1 (Restore) 2 (Transfer)
-j, --no-color Disable colors
-q, --quiet Don't ask, just run
-v, --verbose Enable verbose tar/rsync output
-u, --user-opts Additional tar/rsync options. See tar/rsync --help
If you want spaces in names replace them with //
-o, --override Override default tar/rsync options
--help Print this page
Backup Mode:
Archive Options:
-d, --destination Backup destination path
-n, --filename Backup filename (without extension)
Home Directory:
-H, --home-dir Home directory options: 0 (Include) 1 (Only hidden files and folders) 2 (Exclude)
Archiver Options:
-c, --compression Compression type: gzip bzip2 xz none
-M, --mc-threads Enable multi-core compression via pigz, pbzip2 or pxz. Specify number of threads
Encryption Options:
-E, --encryption Encryption method: openssl gpg
-P, --passphrase Passphrase for encryption
Misc Options:
-g, --generate Generate configuration file (in case of successful backup)
-a, --clean Delete older backups in the destination directory. Specify number of latest backups to keep
-T, --src-dir Specify an alternative source directory to create a non-system backup archive
Restore/Transfer Mode:
Partitions:
-r, --root Target root partition
-m, --mount-opts Comma-separated list of mount options for the root partition
-e, --esp Target EFI system partition
-l, --esp-mpoint Mount point for ESP: /boot/efi /boot
-b, --boot Target /boot partition
-h, --home Target /home partition
-s, --swap Swap partition
-t, --other-parts Specify other partitions. Syntax is mountpoint=partition (e.g /var=/dev/sda3)
If you want spaces in mountpoints replace them with //
Add a trailing @ in any of the above, if it is not empty and you want to clean it (e.g -r /dev/sda2@)
Btrfs Subvolumes:
-R, --rootsubvol Subvolume name for /
-B, --other-subvols Specify other subvolumes (subvolume path e.g /home /var /usr ...)
Bootloaders:
-G, --grub Target grub device
-S, --syslinux Target syslinux device
-F, --efistub Enable EFISTUB/efibootmgr
-L, --bootctl Enable Systemd/bootctl
-k, --kernel-opts Additional kernel options
Restore Mode:
-f, --file Backup file path or url
-y, --username Ftp/http username
-p, --password Ftp/http password
-P, --passphrase Passphrase for decryption
-M, --mc-threads Enable multi-core decompression via pbzip2. Specify number of threads
Transfer Mode:
-H, --home-dir Home directory options: 0 (Include) 1 (Only hidden files and folders) 2 (Exclude)
Misc Options:
-D, --use-genkernel Use genkernel for initramfs building in Gentoo
-W, --ignore-efi Ignore UEFI environment"
exit
shift
;;
--)
shift
break
;;
esac
done
# Give PID to gui wrapper
if [ -n "$BRwrtl" ]; then
echo "$$" > /tmp/wr_pid
fi
# Run if Cancel pressed from the gui wrapper
abort() {
echo "Process ID $(cat /tmp/wr_pid) terminated" > /tmp/wr_log
if [ "$BRmode" = "0" ]; then
clean_tmp_files
exit
elif [ "$BRmode" = "1" ] || [ "$BRmode" = "2" ]; then
post_umt="y"
clean_unmount 2>>/tmp/wr_log
fi
}
trap abort SIGTERM
# Set colors if -j is not given
if [ -z "$BRnocolor" ]; then
NORM='\e[00m'
RED='\e[00;31m'
GREEN='\e[00;32m'
YELLOW='\e[00;33m'
CYAN='\e[00;36m'
BOLD='\033[1m'
fi
# Check if run with root privileges
if [ "$(id -u)" -gt "0" ]; then
print_err "[${RED}ERROR${NORM}] Script must run as root" 0
fi
# Check mode
if [ -z "$BRmode" ]; then
print_err "[${RED}ERROR${NORM}] You must specify a mode" 0
elif [ -n "$BRmode" ] && [ ! "$BRmode" = "0" ] && [ ! "$BRmode" = "1" ] && [ ! "$BRmode" = "2" ]; then
print_err "[${RED}ERROR${NORM}] Wrong mode: $BRmode. Available options: 0 (Backup) 1 (Restore) 2 (Transfer)" 0
fi
clean_tmp_files
# Check /home directory option for Backup and Transfer mode
if [ "$BRmode" = "0" ] || [ "$BRmode" = "2" ] && [ -n "$BRhomedir" ] && [ ! "$BRhomedir" = "0" ] && [ ! "$BRhomedir" = "1" ] && [ ! "$BRhomedir" = "2" ]; then
print_err "[${RED}ERROR${NORM}] Wrong /home directory option: $BRhomedir. Available options: 0 (Include) 1 (Only hidden files and folders) 2 (Exclude)" 0
fi
# Check multi-core threads for Backup and Restore mode
if [ "$BRmode" = "0" ] || [ "$BRmode" = "1" ] && [ -n "$BRmcthreads" ]; then
if [[ ! "$BRmcthreads" =~ ^[0-9]+$ ]] || [ "$BRmcthreads" -lt 1 ] || [ "$BRmcthreads" -gt "$(nproc --all)" ]; then
print_err "[${RED}ERROR${NORM}] Wrong threads number: $BRmcthreads. Available options: 1-$(nproc --all)" 0
fi
fi
# Add tar/rsync user options to the main array, replace any // with space, add only options starting with -
for opt in $BRuseropts; do
if [[ "$opt" == -* ]]; then
BRtropts+=("${opt///\//\ }")
fi
done
# Detect the distro in Backup and Transfer mode by checking for known package manager files
if [ "$BRmode" = "0" ] || [ "$BRmode" = "2" ]; then
if [ -f /etc/yum.conf ] || [ -f /etc/dnf/dnf.conf ]; then
BRdistro="Fedora"
elif [ -f /etc/pacman.conf ]; then
BRdistro="Arch"
elif [ -f /etc/apt/sources.list ]; then
BRdistro="Debian"
elif [ -f /etc/zypp/zypp.conf ]; then
BRdistro="Suse"
elif [ -f /etc/urpmi/urpmi.cfg ]; then
BRdistro="Mandriva"
elif [ -f /etc/portage/make.conf ] || [ -f /etc/make.conf ]; then
BRdistro="Gentoo"
else
BRdistro="Unsupported"
fi
fi
# Backup mode
if [ "$BRmode" = "0" ]; then
# Unset Restore/Transfer mode vars
unset BRroot BResp BRespmpoint BRswap BRboot BRhome BRgrub BRsyslinux BRuri BRusername BRpassword BRrootsubvol BRmountopts BRkernopts BRparts BRsubvols BRefistub BRbootctl
# Show a nice summary
show_summary() {
echo "ARCHIVE"
echo "$BRdestination/$BRname.$BRext ($BRsrc) $mcinfo"
echo -e "\nARCHIVER OPTIONS"
for opt in "${BRtropts[@]}"; do echo "$opt"; done
if [ "$BRsrc" = "/" ]; then
echo -e "\nHOME DIRECTORY"
if [ "$BRhomedir" = "1" ]; then
echo "Only hidden files and folders"
elif [ "$BRhomedir" = "2" ]; then
echo "Exclude"
else
echo "Include"
fi
echo -e "\nFOUND BOOTLOADERS"
# If grub(2)-mkconfig found, probably grub is installed
if which grub-mkconfig &>/dev/null || which grub2-mkconfig &>/dev/null; then echo "Grub"; else BRgrub="n"; fi
# If sys/extlinux found, probably syslinux is installed
if which extlinux &>/dev/null && which syslinux &>/dev/null; then echo "Syslinux"; else BRsyslinux="n"; fi
# Check if efibootmgr is installed
if which efibootmgr &>/dev/null; then echo "EFISTUB/efibootmgr"; else BRefibootmgr="n"; fi
# If bootctl found, probably systemd-boot is available
if which bootctl &>/dev/null; then echo "Systemd/bootctl"; else BRbootctl="n"; fi
# In case none of the above found
if [ -n "$BRgrub" ] && [ -n "$BRsyslinux" ] && [ -n "$BRefibootmgr" ] && [ -n "$BRbootctl" ]; then echo "None or not supported"; fi
fi
# Show older backup directories that we delete later if -a is given
if [ -n "$BRoldbackups" ] && [ -n "$BRclean" ]; then
echo -e "\nDELETE BACKUPS"
for backup in "${BRoldbackups[@]}"; do echo "$backup"; done
fi
}
# Calculate files to create percentage and progress bar
run_calc() {
tar cvf /dev/null "${BRtropts[@]}" "$BRsrc" 2>/dev/null | tee /tmp/filelist
}
# Run tar with given input
run_tar() {
# In case of openssl encryption
if [ -n "$BRencpass" ] && [ "$BRencmethod" = "openssl" ]; then
tar "${BRmainopts[@]}" >(openssl aes-256-cbc -salt -k "$BRencpass" -out "$BRdestination"/"$BRname"."$BRext" 2>> "$BRdestination"/backup.log) "${BRtropts[@]}" "$BRsrc"
# In case of gpg encryption
elif [ -n "$BRencpass" ] && [ "$BRencmethod" = "gpg" ]; then
tar "${BRmainopts[@]}" >(gpg -c --batch --yes --passphrase "$BRencpass" -z 0 -o "$BRdestination"/"$BRname"."$BRext" 2>> "$BRdestination"/backup.log) "${BRtropts[@]}" "$BRsrc"
# Without encryption
else
tar "${BRmainopts[@]}" "$BRdestination"/"$BRname"."$BRext" "${BRtropts[@]}" "$BRsrc"
fi
}
# Generate configuration file
generate_conf() {
echo -e "# Auto-generated configuration file for backup mode. Place it in /etc\n"
echo -e "BRdestination=\"$(dirname "$BRdestination")\"\nBRcompression=\"$BRcompression\""
if [ -n "$BRname" ] && [[ ! "$BRname" == Backup-$(hostname)-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9] ]]; then echo BRname=\"$BRname\"; fi # Strictly check the default filename format
if [ -n "$BRuseropts" ]; then echo BRuseropts=\"$(echo $BRuseropts)\"; fi # trim leading/trailing and multiple spaces
if [ -n "$BRhomedir" ]; then echo BRhomedir=\"$BRhomedir\"; fi
if [ -n "$BRnocolor" ]; then echo BRnocolor=\"Yes\"; fi
if [ -n "$BRverb" ]; then echo BRverb=\"Yes\"; fi
if [ -n "$BRquiet" ]; then echo BRquiet=\"Yes\"; fi
if [ -n "$BRoverride" ]; then echo BRoverride=\"Yes\"; fi
if [ -n "$BRencmethod" ]; then echo -e "BRencmethod=\"$BRencmethod\"\nBRencpass=\"$BRencpass\""; fi
if [ -n "$BRclean" ]; then echo BRclean=\"$BRclean\"; fi
if [ -n "$BRmcthreads" ]; then echo BRmcthreads=\"$BRmcthreads\"; fi
if [ -n "$BRsrc" ] && [ ! "$BRsrc" = "/" ]; then echo BRsrc=\"$BRsrcfull\"; fi
}
# Check user input, exit on error
if [ -n "$BRdestination" ] && [ ! -d "$BRdestination" ]; then
print_err "[${RED}ERROR${NORM}] Directory does not exist: $BRdestination" 0
fi
if [ -n "$BRsrc" ] && [ ! -d "$BRsrc" ]; then
print_err "[${RED}ERROR${NORM}] Directory does not exist: $BRsrc" 0
fi
if [ -n "$BRcompression" ] && [ ! "$BRcompression" = "gzip" ] && [ ! "$BRcompression" = "xz" ] && [ ! "$BRcompression" = "bzip2" ] && [ ! "$BRcompression" = "none" ]; then
print_err "[${RED}ERROR${NORM}] Wrong compression type: $BRcompression. Available options: gzip bzip2 xz none" 0
fi
if [ -n "$BRencmethod" ] && [ ! "$BRencmethod" = "openssl" ] && [ ! "$BRencmethod" = "gpg" ]; then
print_err "[${RED}ERROR${NORM}] Wrong encryption method: $BRencmethod. Available options: openssl gpg" 0
fi
if [ -n "$BRencmethod" ] && [ -z "$BRencpass" ]; then
print_err "[${RED}ERROR${NORM}] You must specify a passphrase" 0
fi
if [ -n "$BRencpass" ] && [ -z "$BRencmethod" ]; then
print_err "[${RED}ERROR${NORM}] You must specify an encryption method" 0
fi
if [ -n "$BRmcthreads" ] && [ -z "$BRcompression" ]; then
print_err "[${RED}ERROR${NORM}] You must specify compression type" 0
elif [ -n "$BRmcthreads" ] && [ "$BRcompression" = "gzip" ] && [ -z "$(which pigz 2>/dev/null)" ]; then
print_err "[${RED}ERROR${NORM}] Package pigz is not installed. Install the package and re-run the script" 0
elif [ -n "$BRmcthreads" ] && [ "$BRcompression" = "bzip2" ] && [ -z "$(which pbzip2 2>/dev/null)" ]; then
print_err "[${RED}ERROR${NORM}] Package pbzip2 is not installed. Install the package and re-run the script" 0
elif [ -n "$BRmcthreads" ] && [ "$BRcompression" = "xz" ] && [ -z "$(which pxz 2>/dev/null)" ]; then
print_err "[${RED}ERROR${NORM}] Package pxz is not installed. Install the package and re-run the script" 0
fi
if [[ ! "$BRclean" =~ ^[0-9]+$ ]] || [ "$BRclean" -lt 0 ] && [ -n "$BRclean" ]; then
print_err "[${RED}ERROR${NORM}] Wrong backups number: $BRclean" 0
fi
# Set some defaults if not given by the user
if [ -z "$BRdestination" ]; then BRdestination="/"; fi
if [ -z "$BRname" ]; then BRname="Backup-$(hostname)-$(date +%Y%m%d-%H%M%S)"; fi
if [ -z "$BRcompression" ]; then BRcompression="gzip"; fi
if [ -z "$BRsrc" ]; then BRsrc="/"; fi
# Set backup subdirectory
BRdestination="$(echo "$BRdestination"/Backup-$(date +%Y-%m-%d) | sed 's://*:/:g')" # Also eliminate multiple forward slashes in the path
if [ ! "$BRsrc" = "/" ]; then
BRsrc="$(echo "$BRsrc" | sed 's://*:/:g')" # Eliminate multiple forward slashes in the path
fi
# Set tar compression options and backup file extension
if [ "$BRcompression" = "gzip" ] && [ -n "$BRmcthreads" ]; then
BRmainopts=(-c -I "pigz -p$BRmcthreads" -vpf)
BRext="tar.gz"
mcinfo="(pigz $BRmcthreads threads)"
elif [ "$BRcompression" = "gzip" ]; then
BRmainopts=(cvpzf)
BRext="tar.gz"
elif [ "$BRcompression" = "xz" ] && [ -n "$BRmcthreads" ]; then
BRmainopts=(-c -I "pxz -T$BRmcthreads" -vpf)
BRext="tar.xz"
mcinfo="(pxz $BRmcthreads threads)"
elif [ "$BRcompression" = "xz" ]; then
BRmainopts=(cvpJf)
BRext="tar.xz"
elif [ "$BRcompression" = "bzip2" ] && [ -n "$BRmcthreads" ]; then
BRmainopts=(-c -I "pbzip2 -p$BRmcthreads" -vpf)
BRext="tar.bz2"
mcinfo="(pbzip2 $BRmcthreads threads)"
elif [ "$BRcompression" = "bzip2" ]; then
BRmainopts=(cvpjf)
BRext="tar.bz2"
elif [ "$BRcompression" = "none" ]; then
BRmainopts=(cvpf)
BRext="tar"
fi
# Set backup file extension based on encryption
if [ -n "$BRencpass" ] && [ "$BRencmethod" = "openssl" ]; then
BRext="$BRext.aes"
elif [ -n "$BRencpass" ] && [ "$BRencmethod" = "gpg" ]; then
BRext="$BRext.gpg"
fi
# Set tar default options
if [ -z "$BRoverride" ] && [ "$BRsrc" = "/" ]; then
BRtropts+=(--sparse \
--acls \
--xattrs \
--exclude=/run/* \
--exclude=/dev/* \
--exclude=/sys/* \
--exclude=/tmp/* \
--exclude=/mnt/* \
--exclude=/proc/* \
--exclude=/media/* \
--exclude=/var/run/* \
--exclude=/var/lock/* \
--exclude=.gvfs \
--exclude=lost+found)
# Needed by Fedora
if [ "$BRdistro" = "Fedora" ]; then
BRtropts+=(--selinux)
fi
fi
BRtropts+=(--exclude="$(basename "$BRdestination")")
# Set /home directory options
if [ "$BRhomedir" = "1" ] && [ "$BRsrc" = "/" ]; then
# Find everything that doesn't start with dot and exclude it
while read item; do
BRtropts+=(--exclude="$item")
done< <(find /home/*/* -maxdepth 0 -iname ".*" -prune -o -print)
elif [ "$BRhomedir" = "2" ] && [ "$BRsrc" = "/" ]; then
BRtropts+=(--exclude=/home/*)
fi
# Check destination for backup directories with older date, strictly check directory name format
if [ -n "$BRclean" ]; then
while read dir; do
if [ "${dir//[^0-9]/}" -lt "${BRdestination//[^0-9]/}" ]; then # Compare the date numbers
BRoldbackups+=("$dir")
fi
done < <(find "$(dirname "$BRdestination")" -mindepth 1 -maxdepth 1 -type d -iname "Backup-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]" | sort -r)
# Remove the first N items given by the user so we don't delete them
BRoldbackups=("${BRoldbackups[@]:$BRclean}")
fi
# Check if backup file already exists and prompt the user to overwrite. If -q is given overwrite automatically
if [ -z "$BRquiet" ]; then
while [ -f "$BRdestination/$BRname.$BRext" ]; do
echo -e "${BOLD}"
read -p "File $BRname.$BRext already exists. Overwrite? [y/N]: $(echo -e "${NORM}")" an
if [ "$an" = "y" ] || [ "$an" = "Y" ]; then
break
elif [ "$an" = "n" ] || [ "$an" = "N" ] || [ -z "$an" ]; then
exit
else
echo -e "${RED}Please enter a valid option${NORM}"
fi
done
fi
# Show summary and prompt the user to continue. If -q is given continue automatically
echo -e "\n${BOLD}[SUMMARY]${CYAN}"
show_summary
echo -ne "${NORM}"
while [ -z "$BRquiet" ]; do
echo -e "${BOLD}"
read -p "Continue? [Y/n]: $(echo -e "${NORM}")" an
if [ "$an" = "y" ] || [ "$an" = "Y" ] || [ -z "$an" ]; then
break
elif [ "$an" = "n" ] || [ "$an" = "N" ]; then
exit
else
echo -e "${RED}Please enter a valid option${NORM}"
fi
done
# Delete older backup directories if -a is given
if [ -n "$BRoldbackups" ] && [ -n "$BRclean" ]; then
for backup in "${BRoldbackups[@]}"; do rm -r "$backup"; done
fi
echo -e "\n${BOLD}[PROCESSING]${NORM}"
print_msg "Preparing" 0
# Restore mode will check and read this file in the archive
if [ "$BRsrc" = "/" ]; then touch /target_architecture.$(uname -m); fi
# Create the destination subdirectory
mkdir -p "$BRdestination"
sleep 1
# Start the log
echo -e "$BRversion\n\n[SUMMARY]\n$(show_summary)\n\n[ARCHIVER]" > "$BRdestination"/backup.log
# Store start time
start=$(date +%s)
# If custom source directory specified, cd in it's parent and backup the child
if [ ! "$BRsrc" = "/" ]; then
cd "$(dirname "$BRsrc")"
BRsrcfull="$BRsrc"
BRsrc="$(basename "$BRsrc")"
fi
# Calculate the number of files
print_msg "Please wait while calculating files" 0
run_calc | while read ln; do a="$((a + 1))" && echo -en "\rCalculating: $a Files"; done
# Store the number of files we found from run_calc
total="$(cat /tmp/filelist | wc -l)"
sleep 1
echo
# Run tar and pipe it through the progress calculation, give errors to log
mode_job="Archiving"
(run_tar 2>> "$BRdestination"/backup.log && echo "$total Files archived successfully" >> "$BRdestination"/backup.log || touch /tmp/error) | pgrs_bar
echo
# Generate configuration file if -g is given and no error occurred
if [ -n "$BRgen" ] && [ ! -f /tmp/error ]; then
echo "Generating backup.conf..."
generate_conf > "$BRdestination"/backup.conf
fi
# Give destination subdirectory full permissions
echo "Setting permissions to $BRdestination"
chmod ugo+rw -R "$BRdestination"
# Calculate elapsed time
elapsed="$(($(($(date +%s)-start))/3600)) hours $((($(($(date +%s)-start))%3600)/60)) min $(($(($(date +%s)-start))%60)) sec"
# Complete the log
echo "Elapsed time: $elapsed" >> "$BRdestination"/backup.log
# Inform the user if error occurred or not
if [ -f /tmp/error ]; then
echo -e "${RED}\nAn error occurred.\n\nCheck $BRdestination/backup.log for details.\nElapsed time: $elapsed${NORM}"
else
echo -e "${CYAN}\nBackup archive and log saved in $BRdestination\nElapsed time: $elapsed${NORM}"
fi
# Give log to gui wrapper
if [ -n "$BRwrtl" ]; then
cat "$BRdestination"/backup.log > /tmp/wr_log
# Give generated configuration file to gui wrapper also
if [ -n "$BRgen" ] && [ ! -f /tmp/error ]; then
echo -e "\n[CONFIGURATION FILE]\n$(cat "$BRdestination"/backup.conf)" >> /tmp/wr_log
fi
fi
clean_tmp_files
# Restore/Transfer Mode
elif [ "$BRmode" = "1" ] || [ "$BRmode" = "2" ]; then
# Unset Backup mode vars
unset BRdestination BRname BRcompression BRgen BRencmethod BRclean BRsrc
# Detect backup archive encryption
detect_encryption() {
if [ "$(file -b "$BRsource")" = "data" ] || file -b "$BRsource" | grep -qw openssl; then
BRencmethod="openssl"
elif file -b "$BRsource" | grep -qw GPG; then
BRencmethod="gpg"
fi
}
# Detect backup archive filetype and set tar options accordingly
detect_filetype() {
print_msg "Checking archive type"
# If archive is encrypted decrypt first, pipe output to 'file'
if [ -n "$BRencpass" ] && [ "$BRencmethod" = "openssl" ]; then
BRtype="$(openssl aes-256-cbc -d -salt -in "$BRsource" -k "$BRencpass" 2>/dev/null | file -b -)"
elif [ -n "$BRencpass" ] && [ "$BRencmethod" = "gpg" ]; then
BRtype="$(gpg -d --batch --passphrase "$BRencpass" "$BRsource" 2>/dev/null | file -b -)"
else
# Check archive directly
BRtype="$(file -b "$BRsource")"
fi
if echo "$BRtype" | grep -q -w gzip; then
BRfiletype="gzip compressed"
BRreadopts=(tfz)
BRmainopts=(xvpfz)
elif echo "$BRtype" | grep -q -w bzip2 && [ -n "$BRmcthreads" ]; then
BRfiletype="bzip2 compressed"
mcinfo="(pbzip2 $BRmcthreads threads)"
BRreadopts=(-I "pbzip2 --ignore-trailing-garbage=1 -p$BRmcthreads" -tf)
BRmainopts=(-I "pbzip2 --ignore-trailing-garbage=1 -p$BRmcthreads" -xvpf)
elif echo "$BRtype" | grep -q -w bzip2; then
BRfiletype="bzip2 compressed"
BRreadopts=(tfj)
BRmainopts=(xvpfj)
elif echo "$BRtype" | grep -q -w XZ; then
BRfiletype="xz compressed"
BRreadopts=(tfJ)
BRmainopts=(xvpfJ)
elif echo "$BRtype" | grep -q -w POSIX; then
BRfiletype="uncompressed"
BRreadopts=(tf)
BRmainopts=(xvpf)
else
BRfiletype="wrong"
fi
}
# Detect the partition table for Syslinux so we can use the corresponding bin files
detect_partition_table_syslinux() {
# Check if the target Syslinux device is a raid array first
if [[ "$BRsyslinux" == *md* ]]; then
BRsyslinuxdev="$BRdevice" # We set BRdevice in install_bootloader
else
BRsyslinuxdev="$BRsyslinux"
fi
# Check the first 8 bytes for EFI PART
if dd if="$BRsyslinuxdev" skip=64 bs=8 count=1 2>/dev/null | grep -qw "EFI PART"; then
BRtable="gpt"
else
BRtable="mbr"
fi
}
# Apply appropriate partition flags for Syslinux and search known locations for bin and com32 Syslinux files.
set_syslinux_flags_and_paths() {
if [ "$BRtable" = "gpt" ]; then
# Set legacy_boot flag in GPT, use gptmbr.bin
echo "Setting legacy_boot flag on partition $BRpartition of $BRdevice" # We set BRpartition in install_bootloader
sgdisk "$BRdevice" --attributes="$BRpartition":set:2 &>> /tmp/restore.log || touch /tmp/error
BRsyslinuxmbr="gptmbr.bin"
else
# Set boot flag in MBR, use mbr.bin
echo "Setting boot flag on partition $BRpartition of $BRdevice" # We set BRpartition in install_bootloader
sfdisk "$BRdevice" -A "$BRpartition" &>> /tmp/restore.log || touch /tmp/error
BRsyslinuxmbr="mbr.bin"
fi
for BIN in /mnt/target/usr/lib/syslinux/"$BRsyslinuxmbr" \
/mnt/target/usr/lib/syslinux/mbr/"$BRsyslinuxmbr" \
/mnt/target/usr/share/syslinux/"$BRsyslinuxmbr"; do
if [ -f "$BIN" ]; then
BRsyslinuxmbrpath="$(dirname "$BIN")"
fi
done
for COM32 in /mnt/target/usr/lib/syslinux/menu.c32 \
/mnt/target/usr/lib/syslinux/modules/bios/menu.c32 \
/mnt/target/usr/share/syslinux/menu.c32; do
if [ -f "$COM32" ]; then
BRsyslinuxcompath="$(dirname "$COM32")"
fi
done
}
# Generate Syslinux configuration file
generate_syslinux_cfg() {
echo -e "UI menu.c32\nPROMPT 0\nMENU TITLE Boot Menu\nTIMEOUT 50"
# Search target system for kernels
for FILE in /mnt/target/boot/*; do
if file -b -k "$FILE" | grep -qw "bzImage"; then
cn=$(echo "$FILE" | sed -n 's/[^-]*-//p') # Cutted kernel name without any prefix (eg without vmlinuz-)
kn=$(basename "$FILE") # Full kernel name (eg vmlinuz-linux)
# Create entries. We set ipn in detect_initramfs_prefix
if [ "$BRdistro" = "Arch" ]; then
echo -e "LABEL arch\n\tMENU LABEL $BRdistro $cn\n\tLINUX ../$kn\n\tAPPEND root=$bl_root $BRkernopts\n\tINITRD ../$ipn-$cn.img"
echo -e "LABEL archfallback\n\tMENU LABEL $BRdistro $cn fallback\n\tLINUX ../$kn\n\tAPPEND root=$bl_root $BRkernopts\n\tINITRD ../$ipn-$cn-fallback.img"
elif [ "$BRdistro" = "Debian" ]; then
echo -e "LABEL debian\n\tMENU LABEL $BRdistro-$cn\n\tLINUX ../$kn\n\tAPPEND root=$bl_root $BRkernopts\n\tINITRD ../$ipn.img-$cn"
elif [ "$BRdistro" = "Fedora" ]; then
echo -e "LABEL fedora\n\tMENU LABEL $BRdistro-$cn\n\tLINUX ../$kn\n\tAPPEND root=$bl_root $BRkernopts\n\tINITRD ../$ipn-$cn.img"
elif [ "$BRdistro" = "Suse" ]; then
echo -e "LABEL suse\n\tMENU LABEL $BRdistro-$cn\n\tLINUX ../$kn\n\tAPPEND root=$bl_root $BRkernopts\n\tINITRD ../$ipn-$cn"
elif [ "$BRdistro" = "Mandriva" ]; then
echo -e "LABEL suse\n\tMENU LABEL $BRdistro-$cn\n\tLINUX ../$kn\n\tAPPEND root=$bl_root $BRkernopts\n\tINITRD ../$ipn-$cn.img"
elif [ "$BRdistro" = "Gentoo" ] && [ -n "$BRgenkernel" ]; then
echo -e "LABEL gentoo\n\tMENU LABEL $BRdistro-$kn\n\tLINUX ../$kn\n\tAPPEND root=$bl_root $BRkernopts\n\tINITRD ../$ipn-$cn"
elif [ "$BRdistro" = "Gentoo" ]; then
echo -e "LABEL gentoo\n\tMENU LABEL $BRdistro-$kn\n\tLINUX ../$kn\n\tAPPEND root=$BRroot $BRkernopts"
fi
fi
done
}
# Set tar default options
set_tar_opts() {
if [ "$BRdistro" = "Fedora" ] && [ -z "$BRoverride" ]; then
BRtropts+=(--selinux --acls "--xattrs-include='*'")
elif [ -z "$BRoverride" ]; then
BRtropts+=(--acls --xattrs)
fi
}
# Run tar with given input
run_tar() {
# In case of openssl encryption
if [ -n "$BRencpass" ] && [ "$BRencmethod" = "openssl" ]; then
openssl aes-256-cbc -d -salt -in "$BRsource" -k "$BRencpass" 2>> /tmp/restore.log | tar "${BRmainopts[@]}" - "${BRtropts[@]}" -C /mnt/target
# In case of gpg encryption
elif [ -n "$BRencpass" ] && [ "$BRencmethod" = "gpg" ]; then
gpg -d --batch --passphrase "$BRencpass" "$BRsource" 2>> /tmp/restore.log | tar "${BRmainopts[@]}" - "${BRtropts[@]}" -C /mnt/target
# Without encryption
else
tar "${BRmainopts[@]}" "$BRsource" "${BRtropts[@]}" -C /mnt/target
fi
}
# Set default rsync options if -o is not given
set_rsync_opts() {
if [ -z "$BRoverride" ]; then
BRtropts+=(--exclude=/run/* \
--exclude=/dev/* \
--exclude=/sys/* \
--exclude=/tmp/* \
--exclude=/mnt/* \
--exclude=/proc/* \
--exclude=/media/* \
--exclude=/var/run/* \
--exclude=/var/lock/* \
--exclude=/home/*/.gvfs \
--exclude=lost+found)
fi
if [ "$BRhomedir" = "1" ]; then
BRtropts+=(--exclude=/home/*/[^.]*)
elif [ "$BRhomedir" = "2" ]; then
BRtropts+=(--exclude=/home/*)
fi
}
# Calculate files to create percentage and progress bar in Transfer mode
run_calc() {
rsync -a --out-format=%n / /mnt/target "${BRtropts[@]}" --dry-run 2>/dev/null | tee /tmp/filelist
}
# Run rsync with given input
run_rsync() {
rsync -aAX --out-format=%n / /mnt/target "${BRtropts[@]}"
}
# Scan normal partitions, lvm, md arrays and sd card partitions
scan_parts() {
for f in $(find /dev -regex "/dev/[vhs]d[a-z][0-9]+"); do echo "$f"; done | sort
for f in $(find /dev/mapper/ -maxdepth 1 -mindepth 1 ! -name "control"); do echo "$f"; done
for f in $(find /dev -regex "^/dev/md[0-9]+$"); do echo "$f"; done
for f in $(find /dev -regex "/dev/mmcblk[0-9]+p[0-9]+"); do echo "$f"; done
for f in $(find /dev -regex "/dev/nvme[0-9]+n[0-9]+p[0-9]+"); do echo "$f"; done
}
# Scan disks, md arrays and sd card devices
scan_disks() {
for f in /dev/[vhs]d[a-z]; do echo "$f"; done
for f in $(find /dev -regex "^/dev/md[0-9]+$"); do echo "$f"; done
for f in $(find /dev -regex "/dev/mmcblk[0-9]+"); do echo "$f"; done
for f in $(find /dev -regex "/dev/nvme[0-9]+n[0-9]+"); do echo "$f"; done
}
# Show a nice summary
show_summary() {
echo "TARGET PARTITION SCHEME"
BRpartitions="Partition|Mountpoint|Filesystem|Size|Options\n$BRroot $BRmap|/|$BRrootfs|$BRrootsize|$BRmountopts"
if [ -n "$BRparts" ]; then
for part in "${BRparts[@]}"; do
BRpart=$(echo "$part" | cut -f2 -d"=")
BRmpoint=$(echo "$part" | cut -f1 -d"=")
# Replace any // with space
BRmpoint="${BRmpoint///\//\ }"
# Find filesystem type
BRpartfs="$(blkid -s TYPE -o value "$BRpart")"
# Find partition size
BRpartsize="$(lsblk -d -n -o size 2>/dev/null "$BRpart" | sed -e 's/ *//')" # Remove leading spaces
BRpartitions="$BRpartitions\n$BRpart|$BRmpoint|$BRpartfs|$BRpartsize"
done
fi
if [ -n "$BRswap" ]; then
BRpartitions="$BRpartitions\n$BRswap|swap"
fi
# Create columns
echo -e "$BRpartitions" | column -t -s '|'
if [ "$BRrootfs" = "btrfs" ] && [ -n "$BRrootsubvol" ]; then
echo -e "\nSUBVOLUMES"
echo "$BRrootsubvol"
if [ -n "$BRsubvols" ]; then
for subvol in "${BRsubvols[@]}"; do echo "$BRrootsubvol$subvol"; done | sort
fi
fi
echo -e "\nBOOTLOADER"
if [ -n "$BRgrub" ]; then
if [ -d "$BRefidir" ]; then
echo "$BRbootloader ($BRgrubefiarch)"
else
echo "$BRbootloader (i386-pc)"
fi
# If the target Grub device is a raid array, show all devices the array contains
if [[ "$BRgrub" == *md* ]]; then
echo Devices: $(grep -w "${BRgrub##*/}" /proc/mdstat | grep -oP '[vhs]d[a-z]')
elif [ ! -d "$BRefidir" ]; then
echo "Device: $BRgrub"
fi
elif [ -n "$BRsyslinux" ]; then
echo "$BRbootloader ($BRtable)"
# If the target Syslinux device is a raid array, show all devices the array contains
if [[ "$BRsyslinux" == *md* ]]; then
echo Devices: $(grep -w "${BRsyslinux##*/}" /proc/mdstat | grep -oP '[vhs]d[a-z]')
else
echo "Device: $BRsyslinux"
fi
elif [ -n "$BRefistub" ] || [ -n "$BRbootctl" ]; then
echo "$BRbootloader"
else
echo "None (WARNING)"
fi
if [ -n "$BRbootloader" ] && [ -n "$BRkernopts" ]; then
echo "Kernel Options: $BRkernopts"
fi
echo -e "\nPROCESS"
if [ "$BRmode" = "1" ]; then
echo "Mode: Restore"
if [ -n "$BRencmethod" ]; then
echo "Archive: $BRfiletype $BRencmethod encrypted $mcinfo"
else
echo "Archive: $BRfiletype $mcinfo"
fi
elif [ "$BRmode" = "2" ]; then
echo "Mode: Transfer"
if [ "$BRhomedir" = "1" ]; then
echo "Home: Only hidden files and folders"
elif [ "$BRhomedir" = "2" ]; then
echo "Home: Exclude"
else
echo "Home: Include"
fi
fi
if [ "$BRdistro" = "Unsupported" ]; then
echo "System: $BRdistro (WARNING)"
elif [ "$BRmode" = "1" ]; then
echo "System: $BRdistro based $target_arch"
elif [ "$BRmode" = "2" ]; then
echo "System: $BRdistro based $(uname -m)"
fi
if [ "$BRdistro" = "Gentoo" ] && [ -z "$BRgenkernel" ]; then
echo "Info: Skip initramfs building"
fi
if [ "$BRmode" = "2" ] && [ -n "$BRtropts" ]; then
echo -e "\nRSYNC OPTIONS"
elif [ "$BRmode" = "1" ] && [ -n "$BRtropts" ]; then
echo -e "\nARCHIVER OPTIONS"
fi
for opt in "${BRtropts[@]}"; do echo "$opt"; done
}