-
Notifications
You must be signed in to change notification settings - Fork 1
/
bcrm.sh
executable file
·3636 lines (3120 loc) · 133 KB
/
bcrm.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
#! /usr/bin/env bash
# shellcheck disable=SC2155,SC2153,SC2015,SC2094,SC2016,SC2034
# Copyright (C) 2017-2022 Marcel Lautenbach {{{
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software
# Foundation, version 3.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
#}}}
# OPTIONS -------------------------------------------------------------------------------------------------------------{{{
unset IFS #Make sure IFS is not overwritten from the outside
export LC_ALL=en_US.UTF-8
export LVM_SUPPRESS_FD_WARNINGS=true
export XZ_OPT= #Make sure no compression is in place, can be set with -z. See Main()
[[ $TERM == unknown || $TERM == dumb ]] && export TERM=xterm
set -o pipefail
shopt -s globstar
#}}}
# CONSTANTS -----------------------------------------------------------------------------------------------------------{{{
declare VERSION=67815ea
declare -r LOG_PATH="/dev/shm/bcrm/"
declare -r LOG_PATH_ON_DISK='/var/log/bcrm'
declare -r F_LOG="$LOG_PATH/bcrm.log"
declare -r F_SCHROOT_CONFIG='/etc/schroot/chroot.d/bcrm'
declare -r F_SCHROOT='bcrm.stretch.tar.xz'
declare -r F_PART_LIST='part_list'
declare -r F_VGS_LIST='vgs_list'
declare -r F_LVS_LIST='lvs_list'
declare -r F_PART_TABLE='part_table'
declare -r F_CHESUM='check.md5'
declare -r F_CONTEXT='context'
declare -r F_VENDOR_LIST='vendor.list'
declare -r F_DEVICE_MAP='device_map'
declare -r F_ROOT_FOLDER_DU='root_folder_du'
declare -r SCHROOT_HOME=/tmp/dbs
declare -r BACKUP_FOLDER=/var/bcrm/backup
declare -r SCRIPTNAME=$(basename "$0")
declare -r SCRIPTPATH=$(dirname "$0")
declare -r PIDFILE="/var/run/$SCRIPTNAME"
declare -r ROOT_DISK=$(lsblk -rpo pkname,mountpoint | grep '\s/$' | cut -d ' ' -f1)
declare -r SRC_NBD=/dev/nbd0
declare -r DEST_NBD=/dev/nbd1
declare -r CLONE_DATE=$(date '+%d%m%y')
declare -r SNAP4CLONE='snap4clone'
declare -r SALT=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 10)
declare -r LUKS_LVM_NAME="${SALT}_${CLONE_DATE}"
declare -r FIFO='/tmp/bcrm.fifo'
declare -r ID_GPT_LVM=e6d6d379-f507-44c2-a23c-238f2a3df928
declare -r ID_GPT_EFI=c12a7328-f81f-11d2-ba4b-00a0c93ec93b
declare -r ID_GPT_LINUX=0fc63daf-8483-4772-8e79-3d69d8477de4
declare -r ID_DOS_EFI=ef
declare -r ID_DOS_LVM='0x8e'
declare -r ID_DOS_LINUX=83
declare -r ID_DOS_FAT32=c
declare -r ID_DOS_EXT='0x5'
declare _RMODE=false
declare MODE="" #clone,backup,restore
#}}}
# PREDEFINED COMMAND SEQUENCES ----------------------------------------------------------------------------------------{{{
declare -r LSBLK_CMD='lsblk -Ppno NAME,KNAME,FSTYPE,UUID,PARTUUID,TYPE,PARTTYPE,MOUNTPOINT,SIZE'
#}}}
# VARIABLES -----------------------------------------------------------------------------------------------------------{{{
# GLOBALS -------------------------------------------------------------------------------------------------------------{{{
declare -A SRCS #[uuid]<dev>:<fs>,<part-uuid>,<part-type>,<disk|part>,<mountpoint>,<used>,<size>
declare -A DESTS #[uuid]<dev>:<fs>,<part-uuid>,<part-type>,<disk|part>,<mountpoint>,<used>,<size>
declare -A CHG_SYS_FILES #Container for system files that needed to be changed during execution
#[<original file path>]<MD5sum>
declare -A MOUNTS #[part-uuid|uuid|dev]mountpoint A mountpoint can existist for each key!
declare -A MNTJRNL
declare -A SRC2DEST #[uuid]uuid
declare -A PSRC2PDEST #[part-uuid]part-uuid
declare -A NSRC2NDEST #[dev]dev
declare -A DEVICE_MAP #Cartesian product of name, kname, dm and disk-by-uuid
declare PVS=() VG_DISKS=() CHROOT_MOUNTS=()
declare FROZEN_MNT=""
#}}}
# FILLED BY OR BECAUSE OF PROGRAM ARGUMENTS ---------------------------------------------------------------------------{{{
declare -A EXT_PARTS EXCLUDES CHOWN
declare REMOVE_PKGS=()
declare PKGS=() #Will be filled with a list of packages that will be needed, depending on given arguments
declare SRCS_ORDER=() DESTS_ORDER=() SRC_EXCLUDES=()
declare SRC_IMG=""
declare DEST_IMG=""
declare IMG_TYPE=""
declare IMG_SIZE=""
declare SRC=""
declare DEST=""
declare VG_SRC_NAME_CLONE=""
declare ENCRYPT_PWD=""
declare HOST_NAME=""
declare EFI_BOOT_IMAGE=""
declare UEFI=false
declare CREATE_LOOP_DEV=false
declare PVALL=false
declare SPLIT=false
declare IS_CHECKSUM=false
declare SCHROOT=false
declare IS_CLEANUP=true
declare ALL_TO_LVM=false
declare UPDATE_EFI_BOOT=false
declare UNIQUE_CLONE=false
declare YES=false
declare MIN_RESIZE=2048 #In 1M units
declare SWAP_SIZE=-1 #Values < 0 mean no change/ignore
declare BOOT_SIZE=-1
declare -A LVM_EXPAND_BY #How much % of free space to use from a VG, e.g. when a dest disk is larger than a src disk.
declare -A LVM_SIZE_TO
#}}}
# CHECKS FILLED BY MAIN -----------------------------------------------------------------------------------------------{{{
declare -A PARAMS=() #All arguments and their (default) values passed via CLI.
declare DISABLED_MOUNTS=()
declare -A TO_LVM=()
declare VG_SRC_NAME=""
declare BOOT_PART=""
declare SWAP_PART=""
declare EFI_PART=""
declare MNTPNT=""
declare TABLE_TYPE=""
declare INTERACTIVE=false
declare HAS_GRUB=false
declare HAS_LUKS=false #If source is encrypted
declare HAS_EFI=false #If the cloned system is UEFI enabled
declare SYS_HAS_EFI=false #If the currently running system has UEFI
declare IS_LVM=false
declare EXIT=0
declare SECTORS_SRC=0
declare SECTORS_DEST=0
declare SECTORS_SRC_USED=0
declare VG_FREE_SIZE=0
declare SYS_CHANGED=false #If source system has been changed, e.g. deactivated hibernation
declare LIVE_CHECKSUMS=true
#}}}
#}}}
# PRIVATE - Only used by PUBLIC functions -----------------------------------------------------------------------------{{{
#--- Display ---{{{
echo_() { #{{{
exec 1>&3 #restore stdout
echo "$1"
exec 3>&1 #save stdout
exec >>$F_LOG 2>&1 #again all to the log
} #}}}
logmsg() { #{{{
local d=$(date --rfc-3339=seconds)
printf "\n%s\t%s\n\n" "[BCRM] ${d}" "${1}" >> $F_LOG
} #}}}
show_usage() { #{{{
local -A usage
printf "\nUsage: $(basename $0) -s <source> -d <destination> [options]\n\n"
printf "\nOPTIONS"
printf "\n-------\n\n"
printf " %-3s %-30s %s\n" "-s," "--source" "The source device or folder to clone or restore from"
printf " %-3s %-30s %s\n" "-d," "--destination" "The destination device or folder to clone or backup to"
printf " %-3s %-30s %s\n" " " "--source-image" "Use the given image as source in the form of <path>:<type>"
printf " %-3s %-30s %s\n" " " "" "For example: '/path/to/file.vdi:vdi'. See below for supported types."
printf " %-3s %-30s %s\n" " " "--destination-image" "Use the given image as destination in the form of <path>:<type>[:<virtual-size>]"
printf " %-3s %-30s %s\n" " " "" "For instance: '/path/to/file.img:raw:20G'"
printf " %-3s %-30s %s\n" " " "" "If you omit the size, the image file must exists."
printf " %-3s %-30s %s\n" " " "" "If you provide a size, the image file will be created or overwritten."
printf " %-3s %-30s %s\n" "-c," "--check" "Create/Validate checksums"
printf " %-3s %-30s %s\n" "-z," "--compress" "Use compression (compression ratio is about 1:3, but very slow!)"
printf " %-3s %-30s %s\n" " " "--split" "Split backup into chunks of 1G files"
printf " %-3s %-30s %s\n" "-H," "--hostname" "Set hostname"
printf " %-3s %-30s %s\n" " " "--remove-pkgs" "Remove the given list of whitespace-separated packages as a final step."
printf " %-3s %-30s %s\n" " " "" "The whole list must be enclosed in \"\""
printf " %-3s %-30s %s\n" "-n," "--new-vg-name" "LVM only: Define new volume group name"
printf " %-3s %-30s %s\n" " " "--vg-free-size" "LVM only: How much space should be added to remaining free space in source VG."
printf " %-3s %-30s %s\n" "-e," "--encrypt-with-password" "LVM only: Create encrypted disk with supplied passphrase"
printf " %-3s %-30s %s\n" "-p," "--use-all-pvs" "LVM only: Use all disks found on destination as PVs for VG"
printf " %-3s %-30s %s\n" " " "--lvm-expand" "LVM only: Have the given LV use the remaining free space."
printf " %-3s %-30s %s\n" " " "" "An optional percentage can be supplied, e.g. 'root:80'"
printf " %-3s %-30s %s\n" " " "" "Which would add 80% of the remaining free space in a VG to this LV"
printf " %-3s %-30s %s\n" " " "--lvm-set-size" "LVM only: Set size of given LV, e.g. 'root:80G'."
printf " %-3s %-30s %s\n" "-u," "--make-uefi" "Convert to UEFI"
printf " %-3s %-30s %s\n" "-w," "--swap-size" "Swap partition size. May be zero to remove any swap partition."
printf " %-3s %-30s %s\n" "-m," "--resize-threshold" "Do not resize partitions smaller than <size> (default 2048M)"
printf " %-3s %-30s %s\n" " " "--schroot" "Run in a secure chroot environment with a fixed and tested tool chain"
printf " %-3s %-30s %s\n" " " "--no-cleanup" "Do not remove temporary (backup) files and mounts."
printf " %-3s %-30s %s\n" " " "" "Useful when tracking down errors with --schroot."
printf " %-3s %-30s %s\n" " " "--disable-mount" "Disable the given mount point in <destination>/etc/fstab."
printf " %-3s %-30s %s\n" " " "" "For instance --disable-mount /some/path. Can be used multiple times."
printf " %-3s %-30s %s\n" " " "--to-lvm" "Convert given source partition or folder to LV. E.g. '/dev/sda1:boot' would be"
printf " %-3s %-30s %s\n" " " "" "converted to LV with the name 'boot'. Can be used multiple times."
printf " %-3s %-30s %s\n" " " "" "Only works for partitions that have a valid mountpoint in fstab"
printf " %-3s %-30s %s\n" " " "" "To convert a folder, e.g /var, to LVM you have to specify the LV size."
printf " %-3s %-30s %s\n" " " "" "For example: '/var:var:5G'."
printf " %-3s %-30s %s\n" " " "--all-to-lvm" "Convert all source partitions to LV. (except EFI)"
printf " %-3s %-30s %s\n" " " "--include-partition" "Also include the content of the given partition to the specified path."
printf " %-3s %-30s %s\n" " " "" "E.g: 'part=/dev/sdX,dir=/some/path/,user=1000,group=10001,exclude=fodler1,folder2'"
printf " %-3s %-30s %s\n" " " "" "would copy all content from /dev/sdX to /some/path."
printf " %-3s %-30s %s\n" " " "" "If /some/path does not exist, it will be created with the given user"
printf " %-3s %-30s %s\n" " " "" "and group ID, or root otherwise. With exclude you can filter folders and files."
printf " %-3s %-30s %s\n" " " "" "This option can be specified multiple times."
printf " %-3s %-30s %s\n" " " "--exclude-folder" "Exclude a folder from source partition or backup."
printf " %-3s %-30s %s\n" " " "" "This option can be specified multiple times."
printf " %-3s %-30s %s\n" " " "--update-efi-boot" "Add a new Entry to EFI NVRAM and make the cloned disk the first boot device."
printf " %-3s %-30s %s\n" " " "" "Use this option if you plan to replace an existing disk with the clone."
printf " %-3s %-30s %s\n" " " "" "Especially if you plan to keep the original disk installed, but the system should"
printf " %-3s %-30s %s\n" " " "" "boot from the clone."
printf " %-3s %-30s %s\n" " " "--efi-boot-iamge" "Path to an existing EFI image, e.g. '\EFI\debian\grub.efi'"
printf " %-3s %-30s %s\n" "-U," "--unique-clone" "For GPT partition tables: Randomize the cloned disk's GUID and all partitions' unique GUIDs."
printf " %-3s %-30s %s\n" " " "" "For MBR partition tables: Randomize the disk identifier only."
printf " %-3s %-30s %s\n" "-q," "--quiet" "Quiet, do not show any output."
printf " %-3s %-30s %s\n" "-h," "--help" "Display this help and exit."
printf " %-3s %-30s %s\n" "-v," "--version" "Show version information for this instance of bcrm and exit."
printf " %-3s %-30s %s\n" "-y," "--yes" "Answer 'yes' to all questions."
printf "\n\nADVANCED OPTIONS"
printf "\n----------------\n\n"
printf " %-3s %-30s %s\n" "-b," "--boot-size" "Boot partition size. For instance: 200M or 4G."
printf " %-3s %-30s %s\n" " " "" "Be careful, the script only checks for the bootable flag,"
printf " %-3s %-30s %s\n" " " "" "Only use with a dedicated /boot partition"
printf "\n\nADDITIONAL NOTES"
printf "\n----------------\n"
printf "\nSize values must be postfixed with a size indcator, e.g: 200M or 4G. The following indicators are valid:\n\n"
printf " %-3s %s\n" "K" "[kilobytes]"
printf " %-3s %s\n" "M" "[megabytes]"
printf " %-3s %s\n" "G" "[gigabytes]"
printf " %-3s %s\n" "T" "[terabytes]"
printf "\nWhen using virtual images you always have to provide the image type. Currently the following image types are supported:\n\n"
printf " %-7s %s\n" "raw" "Plain binary"
printf " %-7s %s\n" "vdi" "Virtual Box"
printf " %-7s %s\n" "qcow2" "QEMU/KVM"
printf " %-7s %s\n" "vmdk" "VMware"
printf " %-7s %s\n\n\n" "vhdx" "Hyper-V"
printf "\nThe following log files are available:\n\n"
printf " %-40s %s\n" "/tmp/bcrm.log" "General procelain log fiile."
printf " %-40s %s\n" "/tmp/bcrm.<partition>.md5.log" "Full log created from md5sum (requires -c)."
printf " %-40s %s\n" "/tmp/bcrm.<partition>.md5.failed.log" "Only files with failed checksum (requires -c)."
printf " %-40s %s\n" "/tmp/bcrm.<partition>.log" "Log file filled by tar when creating or restoring a backup."
printf " %-40s %s\n" "/tmp/bcrm.<src-part>__<dest-part>.log" "Log file filled by rsync during clone."
exit_ 1
} #}}}
# -t: <text>
# Flags defining the type of text and symbol to be displayed
# -c = CURRENT (➤)
# -y = SUCCESS (✔)
# -n = FAIL (✘)
# -i = INFO (i)
# -I = Mark text (-t) for Input
# -u: Update a message indicator, e.g. from status CURRENT to SUCCESS.
message() { #{{{
local OPTIND
local status
local text
local update=false
local is_input=false
clor_current=$(tput bold; tput setaf 3)
clr_yes=$(tput setaf 2)
clor_no=$(tput setaf 1)
clor_info=$(tput setaf 6)
clor_warn=$(tput setaf 3)
clr_rmso=$(tput sgr0)
exec 1>&3 #restore stdout
#prepare
local option
while getopts ':Iriwnucyt:' option; do
case "$option" in
I)
is_input=true
;;
t)
text=" $OPTARG"
;;
y)
status="${clr_yes}✔${clr_rmso}"
tput rc
;;
n)
status="${clor_no}✘${clr_rmso}"
tput rc
;;
w)
status="${clor_warn}!${clr_rmso}"
;;
i)
status="${clor_info}i${clr_rmso}"
;;
u)
update=true
;;
c)
status="${clor_current}➤${clr_rmso}"
tput sc
;;
r)
tput rc
;;
:)
exit_ 5 "Method call error: \t${FUNCNAME[0]}()\tMissing argument for $OPTARG"
;;
?)
exit_ 5 "Method call error: \t${FUNCNAME[0]}()\tIllegal option: $OPTARG"
;;
esac
done
shift $((OPTIND - 1))
status="${status}"
#execute
[[ -n $status ]] && echo -e -n "[ $status ] "
[[ -n $text ]] \
&& text=$(echo "$text" | sed -e 's/^\s*//; 2,$ s/^/ /') \
&& echo -e -n "$text" \
&& tput el \
&& tput ed
[[ $is_input == false ]] && echo
[[ $update == true ]] && tput rc
tput civis
exec 3>&1 #save stdout
exec >>$F_LOG 2>&1 #again all to the log
} #}}}
spinner() { #{{{
local pid="$1"
local msg="$2"
local stat="$3"
local sp
message -u -c -t "$msg [ $stat ]"
sleep 2
[[ $stat == scan ]] && sp=' s sc scascansca sc s sc sca scan sca sc'
[[ $stat == sync ]] && sp=' s sy synsyncsyn sy s sy syn sync syn sy'
while kill -0 $pid 2>/dev/null; do
message -u -c -t "$msg [ ${sp:0:4} ]"
sp=${sp#????}${sp:0:4}
sleep 0.1
done
} #}}}
#}}}
#--- Context ---{{{
vendor_compare() { #{{{
logmsg "vendor_compare"
if (( $# == 2 )); then
eval local -A from="$1"
eval local -A to="$2"
elif (( $# == 1 )); then
local input="$(</dev/stdin)"
eval local -A from="$input"
eval local -A to="$1"
else
return 1
fi
local k
for k in "${!from[@]}"; do
[[ ${from[$k]} == "${to[$k]}" ]] || echo -e "$k has different versions:\n${from[$k]}\n${to[$k]}"
done
} #}}}
vendor_list() { #{{{
logmsg "vendor_list"
local -A v
local tools
IFS=, read -ra tools <<<"${1// /,}"
local t
for t in "${tools[@]}"; do
case "$t" in
gawk)
v[$t]="$($t --version | head -n1 | cut -d ',' -f1)"
;;
rsync)
v[$t]="$($t --version | head -n1 | gawk '{print $1, $2, $3}')"
;;
tar|flock|bc|blockdev|fdisk|sfdisk|parted|fsfreeze)
v[$t]="$($t --version | head -n1)"
;;
'mkfs.vfat'|'mkfs')
{ v[$t]="$($t --version )"; } 2>/dev/null #mkfs pollutes the log otherwise!
;;
lvm)
v[$t]="$(lvs --version | head -n3)"
;;
qemu-img)
v[$t]="$($t --version | head -n1 | gawk '{print $1,$2,$3}')"
;;
locale-gen|git)
;;
*)
return 1
;;
esac
done
local -p v | sed 's/^[^=]*=//' | sed 's/(/(\n/; s/" /"\n/g; s/\[/ [/g'
} #}}}
# Save key/values of context map to file
ctx_save() { #{{{
logmsg "ctx_save"
{
declare -p BOOT_PART
declare -p HAS_GRUB
declare -p SECTORS_SRC
declare -p SECTORS_SRC_USED
declare -p IS_LVM
declare -p IS_CHECKSUM
declare -p HAS_EFI
declare -p TABLE_TYPE
declare -p SRCS_ORDER
declare -p VG_SRC_NAME
} >"$DEST/$F_CONTEXT"
echo "# Backup date: $(date)" >>"$DEST/$F_CONTEXT"
echo "# Version used: $VERSION" >>"$DEST/$F_CONTEXT"
} #}}}
#}}}
#--- Wrappers ---- {{{
# By convention methods ending with a '_' wrap shell functions or commands with the same name.
# $1: <exit code>
# $2: <message>
exit_(){ #{{{
[[ -n $2 ]] && message -n -t "$2"
EXIT=${1:-0}
exit $EXIT
} #}}}
#}}}
#--- Mounting ---{{{
mount_exta_lvm() { #{{{
local OPTIND
local option
while getopts ':s:d:cu' option; do
case "$option" in
s)
local smpnt="$OPTARG"
;;
d)
local dmpnt="$OPTARG"
;;
c)
local create="true"
;;
u)
local update_fstab="true"
;;
:)
exit_ 5 "Method call error: \t${FUNCNAME[0]}()\tMissing argument for $OPTARG"
;;
?)
exit_ 5 "Method call error: \t${FUNCNAME[0]}()\tIllegal option: $OPTARG"
;;
esac
done
shift $((OPTIND - 1))
local -A lvs_dmpaths
local -A dmpath_uuids
while read -r k v; do lvs_dmpaths[$k]="$v"; done <<<$(lvs --no-headings -o lv_name,dm_path "$VG_SRC_NAME_CLONE" | gawk '{print $1,$2}')
while read -r j w; do dmpath_uuids[$j]="$w"; done <<<$(lsblk -nlo path,uuid "$DEST" | gawk '{if ($2) print $1,$2}')
local l='' name='' paht='' uuid=''
for l in "${!TO_LVM[@]}"; do
IFS=: read -r name size fs <<<"${TO_LVM[$l]}"
path="${lvs_dmpaths[$name]}"
uuid="${dmpath_uuids[${path}]}"
if [[ $update_fstab == true && -s "$dmpnt/etc/fstab" && ! $l =~ ^/dev ]]; then
[[ -z $uuid ]] && exit_ 1 "Missing UUID for $name [$path]"
printf "%s\t%s\t%s\terrors=remount-ro\t0\t1\n" "UUID=$uuid" "$l" "$fs" >> "$dmpnt/etc/fstab"
elif [[ -n $path && -n $fs ]]; then
[[ -n $smpnt && -n $dmpnt ]] && rsync -av -f"+ $l" -f"- *" "$smpnt/$l" "$dmpnt"
[[ $create == true ]] && mkdir -p "$dmpnt/$l"
mount_ "$path" -p "$dmpnt/$l"
fi
done
} #}}}
# $1: <part-uuid,uuid,dev>
find_mount_part() { #{{{
local m=''
for m in $(echo "${!MOUNTS[@]}" | tr ' ' '\n' | sort -r | grep -E '^/' | grep -v -E '^/dev/'); do
[[ $1 =~ $m ]] && echo "$m"
done
} #}}}
mount_(){ #{{{
local cmd="mount"
local OPTIND
local src=''
local path=''
if [[ $1 != tmpfs ]]; then
src=$(realpath -s "$1")
mkdir -p "${MNTPNT}/$src" && path=$(realpath -s "${MNTPNT}/$src")
else
local src="$1"
fi
shift
local option
while getopts ':p:t:o:b' option; do
case "$option" in
t)
! mountpoint -q "$src" && cmd+=" -t $OPTARG"
;;
p)
path=$(realpath -s "$OPTARG")
;;
b)
cmd+=" --bind"
;;
o)
cmd+=" -o $OPTARG"
;;
:)
printf "missing argument for -%s\n" "$OPTARG" >&2
;;
?)
printf "illegal option: -%s\n" "$OPTARG" >&2
;;
esac
done
shift $((OPTIND - 1))
mountpoint -q "$src" && cmd+=" --bind"
logmsg "$cmd $src $path"
[[ -n ${MNTJRNL["$src"]} && ${MNTJRNL["$src"]} != "$path" ]] && return 1
[[ -n ${MNTJRNL["$src"]} && ${MNTJRNL["$src"]} == "$path" ]] && return 0
{ $cmd "$src" "$path" && MNTJRNL["$src"]="$path"; } || return 1
} #}}}
umount_() { #{{{
local OPTIND
local cmd="umount -l"
#TODO remove local?
local option=''
while getopts ':R' option; do
case "$option" in
R)
cmd+=" -R"
local OPT_R='true'
;;
:)
printf "missing argument for -%s\n" "$OPTARG" >&2
;;
?)
printf "illegal option: -%s\n" "$OPTARG" >&2
;;
esac
done
shift $((OPTIND - 1))
local mnt=$(realpath -s "$1")
if [[ $# -eq 0 ]]; then
local m=''
for m in "${MNTJRNL[@]}"; do $cmd "$m"; done
return 0
fi
#TODO validate mounts in list and use return instead of exit
logmsg "$cmd ${MNTJRNL[$mnt]}"
local x=${MNTJRNL[$mnt]}
if [[ $OPT_R == true ]]; then
$cmd ${MNTJRNL[$mnt]} || exit_ 1
for f in "${!MNTJRNL[@]}"; do
[[ ${MNTJRNL[$f]} =~ $x ]] && unset MNTJRNL[$f]
done
else
{ $cmd ${MNTJRNL[$mnt]} && unset MNTJRNL[$mnt]; } || exit_ 1
fi
} #}}}
get_mount() { #{{{
local k=$(realpath -s "$1")
[[ -z $k || -z ${MNTJRNL[$k]} ]] && return 1
echo ${MNTJRNL[$k]}
return 0
} #}}}
mount_chroot() { #{{{
logmsg "mount_chroot"
local mp="$1"
umount_chroot
local f
for f in sys dev dev/pts proc run; do
mount --bind "/$f" "$mp/$f"
done
CHROOT_MOUNTS+=("$mp")
} #}}}
umount_chroot() { #{{{
logmsg "umount_chroot"
local f
for f in ${CHROOT_MOUNTS[@]}; do
umount -Rl "$f"
done
} #}}}
#}}}
#--- LVM related --{{{
# $1: <vg-name>
# $2: <src-dev>
# $3: <dest-dev>
vg_extend() { #{{{
logmsg "vg_extend"
local vg_name="$1"
local src="$2"
local dest="$3"
PVS=()
if [[ -d $src ]]; then
src=$(df -P "$src" | tail -1 | gawk '{print $1}')
fi
local e=''
while read -r e; do
local name='' type=''
read -r name type <<<"$e"
[[ -n $(lsblk -no mountpoint "$name" 2>/dev/null) ]] && continue
echo ';' | sfdisk -q "$name" && sfdisk "$name" -Vq
local part=$(lsblk "$name" -lnpo name,type | grep part | gawk '{print $1}')
pvcreate -ff "$part" && vgextend "$vg_name" "$part"
PVS+=("$part")
done < <(lsblk -po name,type | grep disk | grep -Ev "$dest|$src")
} #}}}
# $1: <vg-name>
# $2: <Ref. to GLOABAL array holding VG disks>
vg_disks() { #{{{
logmsg "vg_disks"
local name=$1
local -n disks=$2
local f=''
for f in $(pvs --no-headings -o pv_name,lv_dm_path | grep -E "${name}\-\w+" | gawk '{print $1}' | sort -u); do
disks+=($(lsblk -pnls $f | grep disk | gawk '{print $1}'))
done
} #}}}
#}}}
#--- Registration ---{{{
add_device_links() { #{{{
local kdev=$1
local devlinks=$(find /dev -type l -exec readlink -nf {} \; -exec echo " {}" ';' | grep -w "$kdev" | gawk '{print $2}')
DEVICE_MAP[$kdev]="$devlinks"
local d=''
for d in $devlinks;
do DEVICE_MAP[$d]=$kdev;
done
} #}}}
mounts() { #{{{
logmsg "mounts"
if [[ $_RMODE == false ]]; then
local mp mpnt sdev sid fs spid ptype type mountpoint rest
local ldata=$(lsblk -lnpo name,kname,uuid,partuuid "$SRC")
_(){ #{{{
local s=''
for s in ${!SRCS[@]}; do
sid=$s
IFS=: read -r sdev fs spid ptype type mountpoint rest <<<${SRCS[$s]}
[[ -z ${mountpoint// } ]] && mp="$sdev" || mp="$mountpoint"
mount_ "$mp" && mpnt=$(get_mount "$mp") || exit_ 1 "Could not mount ${mp}."
if [[ -f $mpnt/etc/fstab ]]; then
local dev='' mnt='' fs=''
while read -r dev mnt fs; do
if [[ ! ${fs// } =~ nfs|swap|udf ]]; then
_(){
local name kname uuid partuuid
read -r name kname uuid partuuid <<<$(grep -iE "${dev//*=/}" <<<"$ldata") #Ignore -real, -cow
if [[ -n ${name// } ]]; then
MOUNTS[$mnt]="${uuid}"
[[ -n ${name// } ]] && MOUNTS[${name//*=/}]=$mnt
[[ -n ${partuuid// } ]] && MOUNTS[${partuuid}]=$mnt
[[ -n ${uuid// } ]] && MOUNTS[$uuid]="${mnt}"
fi
};_
fi
done <<<"$(grep -E '^[^;#]' "$mpnt/etc/fstab" | gawk '{print $1,$2,$3}')"
fi
umount_ "$mp"
done
};_ #}}}
else
local files=()
pushd "$SRC" >/dev/null || return 1
_(){ #{{{
local file=''
for file in [0-9]*; do
local k=$(echo "$file" | sed "s/\.[a-z]*$//")
files+=("$k")
done
};_ #}}}
_(){ #{{{
local file=''
for file in "${files[@]}"; do
local i uuid puuid fs type sused dev mnt dir user group
IFS=. read -r i uuid puuid fs type sused dev mnt dir user group <<<"$(pad_novalue $file)"
mnt=${mnt//_//}
MOUNTS[${mnt}]="$uuid"
[[ -n ${dev//NOVALUE/} ]] && MOUNTS[${dev//_//}]=$mnt
[[ -n ${puuid//NOVALUE/} ]] && MOUNTS[${puuid}]=$mnt
[[ -n ${uuid//NOVALUE/} ]] && MOUNTS[$uuid]="$mnt"
done
};_ #}}}
popd >/dev/null || return 1
fi
} #}}}
set_dest_uuids() { #{{{
logmsg "set_dest_uuids"
if [[ -b $DEST && $IS_LVM == true ]]; then
vgchange -an "$VG_SRC_NAME_CLONE"
vgchange -ay "$VG_SRC_NAME_CLONE"
fi
local lvs_list=$(lvs --no-headings -o lv_name,dm_path "$VG_SRC_NAME_CLONE" | gawk '{print $1,$2}')
_is_lvm_candidate() {
local path="$1"
local lv_name='' dm_path='' line=''
while read -r line; do
read -r lv_name dm_path <<<"$line"
if [[ $path == "$dm_path" ]]; then
local l='' name='' _=''
for l in "${!TO_LVM[@]}"; do
if [[ ! (-b $l || $l =~ ^/dev) ]]; then
IFS=: read -r name _ <<<"${TO_LVM[$l]}"
[[ $name == "$lv_name" ]] && return 0
fi
done
fi
done < <(echo "$lvs_list")
return 1
}
local order=()
local order_lvm=()
_update_order() {
local _order=($(lsblk -lno uuid,type $DEST | awk '{if($2 != "lvm" && $1 != "disk"){print $1}}'))
local _order_lvm=($(lsblk -lno uuid,type $DEST | awk '{if($2 == "lvm"){print $1}}'))
local e=''
for e in "${!_order[@]}"; do
[[ ${_order[$e]} == "$1" ]] && order["$e"]="$1" && continue #snapshots get the same UUID. Continue to avoid duplicate entries!
done
local e=''
for e in "${!_order_lvm[@]}"; do
[[ ${_order_lvm[$e]} == "$1" ]] && order_lvm["$e"]="$1" && continue #snapshots get the same UUID. Continue to avoid duplicate entries!
done
}
local name kdev fstype uuid puuid type parttype mountpoint size e
while read -r e; do
read -r name kdev fstype uuid puuid type parttype mountpoint size <<<"$e"
eval local "$kdev" "$name" "$fstype" "$uuid" "$puuid" "$type" "$parttype" "$mountpoint" "$size"
(( ${#TO_LVM[@]} > 0 )) && _is_lvm_candidate $NAME && continue
#Filter all we don't want
[[ $UEFI == true && ${PARTTYPE} =~ $ID_GPT_EFI|${ID_DOS_EFI} ]] && continue;
local mp
[[ -z ${MOUNTPOINT// } ]] && mp="$NAME" || mp="$MOUNTPOINT"
mount_ "$mp" -t "$FSTYPE" || exit_ 1 "Could not mount ${mp}."
local used='' avail=''
read -r used avail <<<$(df --block-size=1K --output=used,size "$NAME" | tail -n -1)
avail=$((avail - used)) #because df keeps 5% for root!
umount_ "$mp"
DESTS[$UUID]="${NAME}:${FSTYPE:- }:${PARTUUID:- }:${PARTTYPE:- }:${TYPE:- }:${avail:- }" #Avail to be checked
_update_order "$UUID"
# [[ ${PVS[@]} =~ $NAME ]] && continue
done < <($LSBLK_CMD "$DEST" $([[ $PVALL == true ]] && echo ${PVS[@]}) | gawk "! /PARTTYPE=\"($ID_DOS_LVM|$ID_DOS_EXT)\"/ && ! /TYPE=\"(disk|crypt)\"/ && ! /FSTYPE=\"(crypto_LUKS|LVM2_member|swap)\"/ {print \$0}" | sort -u -b -k1,1)
DESTS_ORDER=(${order[@]})
DESTS_ORDER+=(${order_lvm[@]})
} #}}}
# $1: partition, e.g. /dev/sda1
get_uuid() { #{{{
if [[ $_RMODE == true ]]; then
({ eval $(grep -e "$1" $F_PART_LIST); echo "$UUID"; })
else
local env=$(blkid -o export "$1")
local uuid=$(eval "$env"; echo "$UUID")
echo "$uuid"
fi
} #}}}
# $2: <File with lsblk dump>
init_srcs() { #{{{
logmsg "init_srcs"
local file="$1"
local order=()
local order_lvm=()
_update_order() {
local _order=($(lsblk -lno uuid,type $SRC | awk '{if($2 != "lvm" && $1 != "disk"){print $1}}'))
local _order_lvm=($(lsblk -lno uuid,type $SRC | awk '{if($2 == "lvm"){print $1}}'))
local e=''
for e in "${!_order[@]}"; do
[[ ${_order[$e]} == "$1" ]] && order["$e"]="$1" && continue #snapshots get the same UUID. Continue to avoid duplicate entries!
done
local e=''
for e in "${!_order_lvm[@]}"; do
[[ ${_order_lvm[$e]} == "$1" ]] && order_lvm["$e"]="$1" && continue #snapshots get the same UUID. Continue to avoid duplicate entries!
done
}
_(){ #{{{
local e=''
while read -r e; do
local name='' kdev='' fstype='' uuid='' puuid='' type='' parttype='' mountpoint='' size=''
read -r name kdev fstype uuid puuid type parttype mountpoint size <<<"$e"
eval local "$name" "$kdev" "$fstype" "$uuid" "$puuid" "$type" "$parttype" "$mountpoint" "$size"
[[ $_RMODE == false ]] && add_device_links "$KNAME"
if [[ $ALL_TO_LVM == true && $FSTYPE == swap && $TYPE == part ]]; then
size=$(to_kbyte $SIZE)
TO_LVM[$NAME]="swap:${size}:${FSTYPE}"
continue;
elif [[ ${TO_LVM[$NAME]} ]]; then TO_LVM[$NAME]+=":$FSTYPE"
elif [[ $FSTYPE == swap ]]; then continue; fi
#Filter all we don't want
[[ $NAME =~ real$|cow$ ]] && continue
if [[ $_RMODE == false ]]; then
local mp=''
{ lvs -o lv_dmpath,lv_role | grep "$NAME" | grep "snapshot" -q; } && continue
[[ -z ${MOUNTPOINT// } ]] && mp="$NAME" || mp="$MOUNTPOINT"
mount_ "$mp" -t "$FSTYPE" || exit_ 1 "Could not mount ${mp}."
local mpnt=$(get_mount $mp) || exit_ 1 "Could not find mount journal entry for $mp. Aborting!" #do not use local, $? will be affected!
local used='' size=''
read -r used <<<$(df -k --output=used "$mpnt" | tail -n -1)
size=$(sector_to_kbyte $(blockdev --getsz "$NAME"))
local l=''
for l in ${!TO_LVM[@]}; do
if [[ -d $mpnt/$l ]]; then
used=$((used - $(to_kbyte $(du -sb $mpnt/$l)) ))
fi
done
umount_ "$mp"
_update_order "$UUID" #TODO On backup restore, SRCS_ORDER is read from context
fi
SRCS[$UUID]="${NAME}:${FSTYPE:- }:${PARTUUID:- }:${PARTTYPE:- }:${TYPE:- }:${MOUNTPOINT:- }:${used:- }:${size:- }"
done < <(echo "$file" | gawk "! /PARTTYPE=\"($ID_DOS_LVM|$ID_DOS_EXT)\"/ && ! /TYPE=\"(disk|crypt)\"/ && ! /FSTYPE=\"(crypto_LUKS|LVM2_member)\"/ {print \$0}" | sort -u -b -k1,1 | sed '/^$/d')
SRCS_ORDER=(${order[@]})
SRCS_ORDER+=(${order_lvm[@]})
};_ #}}}
_(){ #{{{
if [[ $_RMODE == true ]]; then
pushd "$SRC" >/dev/null || return 1
local f=''
for f in [0-9]*; do
local i='' uuid='' puuid='' fs='' type='' sused='' dev='' mnt=''
local sname='' sfstype='' spartuuid='' sparttype='' stype='' mp='' used='' size=''
IFS=. read -r i uuid puuid fs type sused dev mnt <<<"$(pad_novalue "$f")"
IFS=: read -r sname sfstype spartuuid sparttype stype mp used size <<<"${SRCS[$uuid]}"
if [[ $type == part ]]; then
sname=$(grep "$uuid" "$F_PART_LIST" | gawk '{print $1}' | cut -d '"' -f2)
size=$(sector_to_kbyte $(grep "$sname" "$F_PART_TABLE" | grep -o 'size=.*,' | grep -o '[0-9]*'))
fi
SRCS[$uuid]="${sname//NOVALUE/}:${sfstype//NOVALUE/}:${spartuuid//NOVALUE/}:${sparttype//NOVALUE/}:${stype//NOVALUE/}:${mp//NOVALUE/}:${sused//NOVALUE/}:${size//NOVALUE/}"
done
fi
};_ #}}}
} #}}}
#}}}
#--- Post cloning ---{{{
# $1: <mount point>
# $2: "<dest-dev>"
# $3: "<packages to install>"
grub_install() { #{{{
logmsg "grub_install"
chroot "$1" bash -c "debconf-set-selections <<< 'grub-pc grub-pc/install_devices multiselect $2'
DEBIAN_FRONTEND=noninteractive apt-get install -y $3
if [[ $HAS_EFI == true ]]; then
grub-install --recheck --target=x86_64-efi --efi-directory=/boot/efi $2
else
grub-install --recheck $2
fi
update-initramfs -u -k all
update-grub" &>> $F_LOG
} #}}}
# $1: <mount point>
# $2: <boot image>
update_efi_boot() { #{{{
logmsg "update_efi_boot"
local images=($1/boot/**/EFI/**/*.efi)
local image_path="$2"
_find_image() {
local path='' i=''
for i in ${!images[@]}; do
path="\\EFI$(echo ${images[$i]//*EFI/} | tr / \\ 2>/dev/null)"
[[ "$path" == "$image_path" ]] && return 0
done
return 1
}
if [[ -z ${image_path// } ]]; then
message -i -t "Available EFI images:"
local i=''
for i in ${!images[@]}; do
message -i -t "$i -- ${images[$i]}"
done
message -I -i -t "Select EFI image [0-$i]: "
local nr=''
read -r nr
if [[ $nr -ge 0 && $nr -le $i ]]; then
image_path="\\EFI$(echo ${images[$i]//*EFI/} | tr / \\ 2>/dev/null)"
else
logmsg "Invalid selection. No changes to NVRAM applied!"
return 1
fi
else
_find_image || { logmsg "Boot image $EFI_BOOT_IMAGE not found. No changes applied!"; return 1; }
fi
boot_order=$(efibootmgr | grep BootOrder | gawk '{print $2}')
efibootmgr -c -L "bcrm_$CLONE_DATE" -d "$DEST" -l "$image_path"
boot_id=$(efibootmgr -v | tail -n1 | gawk '{print $1}' | grep -Eo '[0-9]*')
bootorder=$boot_id,$bootorder
} #}}}
# $1: <mount point>