-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy.sh
More file actions
executable file
·1850 lines (1744 loc) · 87.5 KB
/
Copy pathdeploy.sh
File metadata and controls
executable file
·1850 lines (1744 loc) · 87.5 KB
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
#
# linux-backup-system — restore-verified multi-layer Linux backups for every distro and boot layout
# https://github.com/doug445/linux-backup-system
#
# Copyright (c) 2026 William MacKinnon <spilled-bowline0j@icloud.com>
# SPDX-License-Identifier: MIT
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# deploy.sh — policy-aware installer for linux-backup-system.
#
# Usage:
# sudo ./deploy.sh --dry-run detect + print the plan, change nothing
# sudo ./deploy.sh install packages, scripts, config, units
#
# Auto-detects the distro family and package manager (Debian/Ubuntu/Mint,
# Fedora/Asahi, Arch/Manjaro, openSUSE), the root filesystem (btrfs -> snapper
# and send/receive replicas; anything else -> Timeshift), the backup drive and
# whether it is removable (ad-hoc: timers masked) or installed (scheduled),
# a hand-written borg setup (never overwritten), and the architecture.
#
# Environment overrides:
# BACKUP_MOUNT=/path/to/backup — force a specific backup mount path
# FORCE_BORG=1 — replace a hand-written borg setup (a copy is kept)
# SCHEDULE_MODE=adhoc|scheduled — override the drive-type detection
# Run by sh (dash), zsh or `bash`-less invocation: re-exec under bash — the
# shebang is ignored when a script is handed to another shell by name.
[ -n "${BASH_VERSION:-}" ] || exec bash "$0" "$@"
set -euo pipefail
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'
log() { echo -e "${GREEN}[DEPLOY]${NC} $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
err() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
# This suite drives Linux-only tooling (snapper, borg units, systemd timers,
# udev rules). Bail out early and clearly if we are not on Linux at all —
# otherwise the first symptom is a confusing "/etc/os-release not found".
if [ "$(uname -s)" != "Linux" ]; then
err "This deploy script must run on the Linux machine being backed up."
err "Detected host OS: $(uname -s) $(uname -m) — not Linux."
err "Copy this directory to the target box and run it there, e.g.:"
err " rsync -a ./ user@asahi-host:~/linux-backup-system/"
err " ssh user@asahi-host 'cd ~/linux-backup-system && sudo ./deploy.sh'"
exit 1
fi
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# The shared library: one package map and one installer for the deploy and for
# every script it deploys, so what deploy.sh installs is what the scripts check.
# shellcheck disable=SC1091
. "$SCRIPT_DIR/backup-common.sh" || { echo "FATAL: backup-common.sh missing next to deploy.sh" >&2; exit 1; }
CAPACITY_HEADROOM_PCT="${CAPACITY_HEADROOM_PCT:-20}"; CAPACITY_RECOMMEND_X="${CAPACITY_RECOMMEND_X:-2}"
# The desktop user this deploy is for: sudo, doas and pkexec each say it
# differently; under su or a unit only logind knows; `logname` fails on most
# Wayland desktops and everything then landed in /root (autostart, rc files,
# a mount chowned to root).
SUDO_USER="${SUDO_USER:-${DOAS_USER:-}}"
[ -z "$SUDO_USER" ] && [ -n "${PKEXEC_UID:-}" ] && SUDO_USER=$(id -nu "$PKEXEC_UID" 2>/dev/null || true)
[ -z "$SUDO_USER" ] && SUDO_USER=$(loginctl list-sessions --no-legend 2>/dev/null | awk '$3 != "" && $3 != "root" {print $3; exit}' || true)
[ -z "$SUDO_USER" ] && SUDO_USER=$(logname 2>/dev/null || true)
[ -z "$SUDO_USER" ] && SUDO_USER=root
USER_HOME=$(getent passwd "$SUDO_USER" 2>/dev/null | cut -d: -f6)
[ -n "$USER_HOME" ] || USER_HOME=/root
DRY=0
for _a in "$@"; do
case "$_a" in
--dry-run|-n) DRY=1 ;;
-h|--help) sed -n '27,42p' "$0"; exit 0 ;;
*) echo "unknown argument: $_a" >&2; exit 2 ;;
esac
done
[ "$(id -u)" -eq 0 ] || { err "Must run as root: sudo ./deploy.sh"; exit 1; }
# bash reads a running script by file offset; overwriting one in place feeds
# the running root process shifted bytes of the new file — arbitrary lines
# (a prune, a subvolume delete) at the wrong moment. Scripts are installed
# with install(1) (new inode), and never while one of them is running.
# "Running" is decided by the lock every layer holds for its whole run, not by
# matching command lines: `pgrep -f` also matched an editor, a pager, or any
# shell whose -c string merely named the script — deploy refused to run from
# the very terminal that had just typed the path.
backup_lock_held() {
local l
for l in "${BX_LOCK_FILE:-/var/lock/backup-system.lock}" /var/lock/borg-backup.lock; do # the second: pre-3.9 borg-backup.sh
[ -e "$l" ] || continue
flock -n "$l" true 2>/dev/null || return 0
done
return 1
}
if (( ! DRY )) && backup_lock_held; then
err "a backup is running (its lock is held) — wait for it to finish, then re-run deploy.sh"
exit 1
fi
###############################################################################
# Detect distro family
###############################################################################
detect_distro() {
if [ ! -r /etc/os-release ]; then
err "Cannot detect distro (/etc/os-release not found or unreadable)"
err "Every systemd Linux ships this file; are you on the right machine?"
exit 1
fi
. /etc/os-release
# Match on ID first, then on each word of ID_LIKE, so derivatives resolve
# to their parent family (Fedora Asahi Remix, Nobara, CachyOS, Zorin, ...).
DISTRO_FAMILY=""
for _id in "${ID:-}" ${ID_LIKE:-}; do
case "$_id" in
ubuntu|linuxmint|debian|pop)
DISTRO_FAMILY="debian"
;;
fedora|fedora-asahi-remix|rhel|centos|asahi)
DISTRO_FAMILY="fedora"
;;
manjaro|arch|endeavouros)
DISTRO_FAMILY="arch"
;;
opensuse*|suse|sles)
DISTRO_FAMILY="suse"
;;
*)
continue
;;
esac
break
done
if [ -z "$DISTRO_FAMILY" ]; then
err "Unknown distro: ID=${ID:-unknown} ID_LIKE=${ID_LIKE:-none}"
err "Supported families: debian/ubuntu/mint, fedora/asahi, arch/manjaro, opensuse"
err "To add yours, see docs/TROUBLESHOOTING.md 'Hand-rolling a fix for your setup', then run"
err " sudo ./backup-diag.sh -o backup-diag.md"
err "and attach that file to the issue — it is the report the fix is built from."
exit 1
fi
DISTRO_NAME="${PRETTY_NAME:-${ID:-unknown}}"
}
###############################################################################
# Detect if ecryptfs is in use
###############################################################################
detect_ecryptfs() {
HAS_ECRYPTFS=false
if mount | grep -q ecryptfs 2>/dev/null; then
HAS_ECRYPTFS=true
elif [ -d "/home/.ecryptfs" ]; then
HAS_ECRYPTFS=true
fi
}
###############################################################################
# Detect filesystem type (btrfs vs ext4 etc)
###############################################################################
detect_filesystem() {
ROOT_FSTYPE=$(findmnt -n -o FSTYPE / 2>/dev/null || echo "unknown")
HAS_BTRFS=false
HAS_SNAPPER=false
if [ "$ROOT_FSTYPE" = "btrfs" ]; then
HAS_BTRFS=true
if command -v snapper &>/dev/null && snapper list-configs &>/dev/null 2>&1; then
HAS_SNAPPER=true
fi
fi
}
###############################################################################
# Dependencies — installed as soon as the box is detected, before anything
# that needs them (the drive set-up needs mkfs.btrfs and cryptsetup; the layers
# need borg, rsync, snapper or timeshift; the tray needs GTK + AppIndicator).
#
# Required tools are installed together and verified by `command -v` after
# the install; missing any of them aborts the deploy with the package list.
# Optional layers are installed one at a time so a package the distro does not
# carry (backintime on Arch is AUR-only) costs a warning, not the deploy.
# A dry run only reports what it would install.
###############################################################################
install_dependencies() {
local required=(borg rsync cryptsetup btrfs mkfs.btrfs findmnt lsblk sfdisk wipefs blkid udevadm)
local optional=(backintime)
[ "$HAS_BTRFS" = true ] && optional+=(snapper)
[ "$HAS_BTRFS" = false ] && optional+=(timeshift)
[ "$HAS_ECRYPTFS" = true ] && optional+=(mount.ecryptfs)
export BX_DEP_DRYRUN="$DRY"
log "Dependencies for $DISTRO_NAME ($DISTRO_FAMILY): required ${required[*]}"
if ! bx_ensure_deps "${required[@]}" 2>&1 | sed 's/^/ /'; then :; fi
if [ "${PIPESTATUS[0]}" -ne 0 ] && (( ! DRY )); then
err "Required tools could not be installed — cannot continue."
[ "$DISTRO_FAMILY" = arch ] && err "On Arch/Manjaro a stale package database is the usual cause: run pacman -Syu first, then re-run deploy.sh."
exit 1
fi
local tool
for tool in "${optional[@]}"; do
if ! bx_ensure_deps "$tool" 2>&1 | sed 's/^/ /'; then :; fi
if [ "${PIPESTATUS[0]}" -ne 0 ] && (( ! DRY )); then
case "$tool" in
backintime) warn "Back In Time is not installable here (Arch: AUR — yay -S backintime). The BIT layer is deployed but will not run until it is." ;;
timeshift) warn "Timeshift is not installable here (Arch: AUR — yay -S timeshift). Non-btrfs local snapshots are off until it is." ;;
snapper) warn "snapper could not be installed; btrfs replicas still run, snapper timeline snapshots are off." ;;
*) warn "$tool could not be installed." ;;
esac
fi
done
# snapper may have just arrived: re-detect, and say how to configure it.
if [ "$HAS_BTRFS" = true ] && [ "$HAS_SNAPPER" = false ] && command -v snapper >/dev/null 2>&1; then
if snapper list-configs >/dev/null 2>&1; then HAS_SNAPPER=true
else warn "snapper is installed but has no config — create one with: sudo snapper -c root create-config /"; fi
fi
install_tray_dependencies
}
# The tray is Python + GTK3 + AppIndicator3 via GObject introspection; those
# are not commands, so they are probed by importing them.
tray_deps_present() {
python3 -c 'import gi; gi.require_version("Gtk", "3.0"); gi.require_version("AppIndicator3", "0.1"); from gi.repository import Gtk, AppIndicator3' >/dev/null 2>&1
}
install_tray_dependencies() {
if ! { [ -d /usr/share/xsessions ] || [ -d /usr/share/wayland-sessions ] || [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ]; }; then
log " no graphical session on this host — tray dependencies not installed"; return
fi
if tray_deps_present; then log " tray dependencies present (python3, GTK3, AppIndicator3)"; return; fi
local pkgs alt=""
case "$DISTRO_FAMILY" in
# Debian/Ubuntu/Mint ship the maintained Ayatana fork; the legacy
# gir1.2-appindicator3-0.1 is gone from newer releases. Try the fork,
# then the legacy name.
debian) pkgs="python3 python3-gi gir1.2-gtk-3.0 gir1.2-ayatanaappindicator3-0.1"; alt="python3 python3-gi gir1.2-gtk-3.0 gir1.2-appindicator3-0.1" ;;
fedora) pkgs="python3 python3-gobject gtk3 libappindicator-gtk3" ;;
arch) pkgs="python python-gobject gtk3 libappindicator-gtk3" ;;
suse) pkgs="python3 python3-gobject python3-gobject-Gdk typelib-1_0-Gtk-3_0 typelib-1_0-AppIndicator3-0_1" ;;
*) warn "no tray packages known for family '$DISTRO_FAMILY' — the tray needs python3 + GTK3 + AppIndicator3 typelibs"; return ;;
esac
if (( DRY )); then log " (dry-run) would install tray dependencies: $pkgs"; return; fi
log " installing tray dependencies: $pkgs"
# shellcheck disable=SC2086
if ! eval "$(bx_pkg_install_cmd) $pkgs" >/dev/null 2>&1 || ! tray_deps_present; then
if [ -n "$alt" ] && eval "$(bx_pkg_install_cmd) $alt" >/dev/null 2>&1 && tray_deps_present; then
log " tray dependencies installed (legacy AppIndicator3): $alt"
else
warn "tray dependencies did not install — the tray will not start until they do: $pkgs"
fi
fi
case "$(loginctl show-user "$SUDO_USER" -p Desktop --value 2>/dev/null)${XDG_CURRENT_DESKTOP:-}" in
*GNOME*|*gnome*) warn "GNOME shows AppIndicator trays only with the 'AppIndicator and KStatusNotifierItem Support' extension installed" ;;
esac
}
###############################################################################
# Detect backup mount path
###############################################################################
# adopt_label_mount DEV MOUNT — the labelled drive is mounted at MOUNT. Under
# /run/media or /media it was the desktop's automount: a per-user tmpfs path
# that the attach unit would then mkdir as root at boot, after which udisks
# refuses to mount ANY removable media for that user. Remount it at /mnt/backup.
adopt_label_mount() {
local dev="$1" mnt="$2"
case "$mnt" in
/run/media/*|/media/*)
# the same filesystem is also mounted at /mnt/backup (by hand, or by
# the drive-attach unit beside a desktop automount): that is the mount
if [ "$(findmnt -rno SOURCE --mountpoint /mnt/backup 2>/dev/null | sed 's/\[.*//')" = "$dev" ]; then
BACKUP_MOUNT=/mnt/backup
log "the backup drive is mounted at /mnt/backup (the desktop's mount at $mnt is not used)"
return
fi
if (( DRY )) || [ ! -t 0 ]; then
warn "the backup drive is mounted by the desktop at $mnt — that path cannot be the backup mount. Unmount it (or run deploy.sh on a terminal to have it remounted at /mnt/backup)."
BACKUP_MOUNT=/mnt/backup; WAITING_FOR_DRIVE=1
return
fi
log "the backup drive is mounted by the desktop at $mnt — remounting it at /mnt/backup"
umount "$mnt" 2>/dev/null || { err "could not unmount $mnt (open files?) — close them and re-run"; BACKUP_MOUNT=/mnt/backup; WAITING_FOR_DRIVE=1; return; }
BACKUP_MOUNT=/mnt/backup
mount_backup_fs "$dev" || { WAITING_FOR_DRIVE=1; return; }
;;
*) BACKUP_MOUNT="$mnt"
log "Detected backup mount from volume label: $BACKUP_MOUNT" ;;
esac
}
# find_backup_by_contents — "SOURCE<TAB>MOUNT" of a mounted filesystem that
# already holds this suite's backups although it has no Borg-backup label (a
# drive set up by hand, or shared with another machine): a borg repository,
# this host's Back In Time tree, or the test bed's config. This machine's own
# boot chain and data mounts are never candidates. Desktop automounts are
# found too; adopt_label_mount moves them to /mnt/backup.
find_backup_by_contents() {
local m src
while read -r m src; do
m=$(printf '%b' "$m") # findmnt -r writes a space as \x20
case "$m" in /|/boot|/boot/*|/efi|/home|/home/*|/usr|/var|/var/*|/srv|/opt|/tmp|/proc|/sys|/dev|/run/user/*) continue ;; esac
{ [ -f "$m/borg-backup/config" ] || [ -d "$m/backintime/$(hostname)" ] || [ -f "$m/testbed/testbed.conf" ]; } || continue
printf '%s\t%s\n' "$src" "$m"
return 0
done < <(findmnt -rno TARGET,SOURCE -t btrfs,ext4,xfs,exfat,vfat 2>/dev/null | sed 's/\[.*//')
return 1
}
detect_backup_mount() {
# Priority 1: Environment variable override
if [ -n "${BACKUP_MOUNT:-}" ]; then
log "Using BACKUP_MOUNT from environment: $BACKUP_MOUNT"
return
fi
# Priority 2: an existing /etc/backup-system.conf. Mounted: use it. Not
# mounted: this host already has a drive, it is just not connected — keep
# the configured path so units and config are not rewritten to a default,
# and only offer the set-up flow as an alternative.
if [ -r /etc/backup-system.conf ]; then
local existing_mount
existing_mount=$(. /etc/backup-system.conf 2>/dev/null; echo "${BACKUP_MOUNT:-}")
if [ -n "$existing_mount" ] && mountpoint -q "$existing_mount" 2>/dev/null && ! bx_mount_is_live "$existing_mount"; then
# The drive was yanked while mounted: the mount answers "yes" but
# its device is gone. Writes into it vanish, and treating it as
# mounted would make the drive-type detection guess. Clear it.
warn "$existing_mount is a dead mount — its drive was unplugged while mounted. Clearing it."
if (( DRY )); then
log " (dry run: a real run lazily unmounts it and closes the LUKS mapping)"
elif [ -x "$SCRIPT_DIR/borg-backup-drive-detach.sh" ]; then
BX_CONFIG=/etc/backup-system.conf bash "$SCRIPT_DIR/borg-backup-drive-detach.sh" | sed 's/^/ /'
fi
fi
if [ -n "$existing_mount" ] && bx_mount_is_live "$existing_mount"; then
BACKUP_MOUNT="$existing_mount"
log "Detected backup mount from /etc/backup-system.conf: $BACKUP_MOUNT"
if cap_msg=$(bx_check_backup_capacity); then
case "$cap_msg" in *"OK but small"*) warn "$cap_msg" ;; *) log "$cap_msg" ;; esac
else
err "$cap_msg"
err "The configured drive cannot hold one full backup; every backup script will refuse to write to it. Replace it (a blank drive is offered below when connected)."
fi
offer_blank_drive
return
fi
if [ -n "$existing_mount" ]; then
BACKUP_MOUNT="$existing_mount"
WAITING_FOR_DRIVE=1
warn "Configured backup drive is not connected (nothing mounted at $BACKUP_MOUNT)."
local blanks; blanks=$(blank_hotplug_disks | tr '\n' ' ')
[ -n "$blanks" ] && log "New blank drive connected: ${blanks% }"
if (( DRY )) || [ ! -t 0 ]; then
log "Continuing with the configured drive; connect it and re-run to finish (recovery scripts, first backup)."
return
fi
echo ""
echo " 1) Continue — install/update everything; connect the drive later (default)"
echo " 2) Set up a different drive now${blanks:+ (blank drive seen: ${blanks% })}"
ask "Choice [1/2]: "
if [ "$REPLY" = 2 ]; then WAITING_FOR_DRIVE=0; BACKUP_MOUNT=/mnt/backup; prepare_backup_drive "${blanks%% *}"; fi
return
fi
fi
# Priority 3: Look for mounted volumes labeled Borg-backup
local label_dev
label_dev=$(blkid -L "Borg-backup" 2>/dev/null || true)
if [ -n "$label_dev" ]; then
local label_mount
label_mount=$(findmnt -n -o TARGET "$label_dev" 2>/dev/null || true)
if [ -n "$label_mount" ]; then
adopt_label_mount "$label_dev" "$label_mount"
return
fi
# Try the LUKS mapper device
for mapper in /dev/mapper/luks-*; do
[ -b "$mapper" ] || continue
label_mount=$(findmnt -n -o TARGET "$mapper" 2>/dev/null || true)
if [ -n "$label_mount" ]; then
local check_label
check_label=$(lsblk -n -o LABEL "$mapper" 2>/dev/null || true)
if [ "$check_label" = "Borg-backup" ]; then
adopt_label_mount "$mapper" "$label_mount"
return
fi
fi
done
fi
# Priority 3b: an unlabeled drive that already holds this suite's backups
local found
if found=$(find_backup_by_contents); then
log "found a backup drive by its contents (no Borg-backup label): ${found%%$'\t'*} at ${found#*$'\t'}"
adopt_label_mount "${found%%$'\t'*}" "${found#*$'\t'}"
return
fi
# Priority 4: Check /mnt/backup
if mountpoint -q /mnt/backup 2>/dev/null; then
BACKUP_MOUNT="/mnt/backup"
log "Using default backup mount: $BACKUP_MOUNT"
return
fi
# Priority 5: no drive is mounted anywhere. Set one up now, or install
# first and set it up later (the dry run and a non-interactive session
# always take the second path).
BACKUP_MOUNT="/mnt/backup"
if (( DRY )); then
log "No backup drive mounted — a real run would offer to set one up; planning with $BACKUP_MOUNT"
WAITING_FOR_DRIVE=1
return
fi
if [ ! -t 0 ]; then
warn "No backup drive mounted and no terminal to ask on — installing now; re-run deploy.sh with the drive connected."
WAITING_FOR_DRIVE=1
return
fi
prepare_backup_drive
}
###############################################################################
# Restart a running tray so the deploying user sees the build just installed.
#
# The tray is a long-lived desktop process; installing a new file under it
# changes nothing until it restarts, and a stale build once kept reporting
# "Back in Time running" for hours after the fix had been deployed. The new
# instance needs the user's desktop session (DISPLAY, WAYLAND_DISPLAY, the
# session bus), which root does not have — so it is read from the old
# process's own environment before that process is stopped. Exact pids only:
# a pattern match would also hit any shell whose command line names the tray.
###############################################################################
# tray_session_env PID — the desktop-session variables of one of the user's processes
tray_session_env() {
tr '\0' '\n' < "/proc/$1/environ" 2>/dev/null \
| grep -E '^(DISPLAY|WAYLAND_DISPLAY|DBUS_SESSION_BUS_ADDRESS|XDG_RUNTIME_DIR|XDG_SESSION_TYPE|XAUTHORITY)=' \
| tr '\n' ' ' || true
}
# start_tray ENVS VERB — launch the tray in the user's session and prove it stayed up
start_tray() {
local envs="$1" verb="$2" out
out=$(mktemp /tmp/backup-tray-start.XXXXXX); chmod 644 "$out"
# shellcheck disable=SC2086 # envs is a list of KEY=VALUE words by construction
runuser -u "$SUDO_USER" -- env $envs setsid /usr/local/bin/backup-tray >"$out" 2>&1 </dev/null &
sleep 3
if pgrep -u "$SUDO_USER" -f '^python3 /usr/local/bin/backup-tray$' >/dev/null 2>&1; then
log " tray $verb (pid $(pgrep -u "$SUDO_USER" -f '^python3 /usr/local/bin/backup-tray$' | head -1))"
[ -s "$out" ] && sed 's/^/ [tray] /' "$out"
else
warn " tray did not stay up — start it from the desktop: /usr/local/bin/backup-tray &"
[ -s "$out" ] && sed 's/^/ [tray] /' "$out" >&2
fi
rm -f "$out"
}
restart_tray() {
local pids pid envs="" spid
pids=$(pgrep -u "$SUDO_USER" -f '^python3 /usr/local/bin/backup-tray$' 2>/dev/null || true)
if [ -z "$pids" ]; then
# Not running: start it now in the user's graphical session when there
# is one (its environment read from a process of that session), instead
# of leaving the first tray to the next login.
(( DRY )) && { log " (dry run: a real run starts the tray in $SUDO_USER's desktop session, if one is logged in)"; return 0; }
for spid in $(pgrep -u "$SUDO_USER" 2>/dev/null); do
envs=$(tray_session_env "$spid")
case "$envs" in *DBUS_SESSION_BUS_ADDRESS=*) case "$envs" in *DISPLAY=*) break ;; esac ;; esac
envs=""
done
if [ -z "$envs" ]; then
log " no desktop session for $SUDO_USER — the tray starts at the next login (autostart)"
return 0
fi
start_tray "$envs" started
return 0
fi
for pid in $pids; do
envs=$(tray_session_env "$pid")
kill "$pid" 2>/dev/null || true
done
sleep 1
if [ -z "$envs" ]; then
warn " tray stopped but its session environment could not be read — start it from the desktop: /usr/local/bin/backup-tray &"
return 0
fi
start_tray "$envs" "restarted with the new build"
}
###############################################################################
# Backup drive set-up: connect, identify, (optionally) encrypt, format, mount.
#
# Every step here is interactive. The one destructive step — formatting — is
# gated behind the device path typed back and the word ERASE, and is refused
# outright on a disk that holds a mounted filesystem, active swap, or an fstab
# or crypttab entry. Encryption is never done here: a drive that should be
# encrypted is encrypted by the user with GNOME Disks or GParted first, or in
# place afterwards with LinuxLocker; this script only adopts the result.
###############################################################################
WAITING_FOR_DRIVE=0
DRIVE_SETUP_DONE=0
DRIVE_KEYFILE=""
FORMATTED_PART=""
PLAIN_DRIVE_ACCEPTED=0
# A plain backup drive holds a readable copy of every file on the machine.
# Say so, and go ahead only on an explicit acceptance.
accept_plain_risk() {
echo ""
echo -e "${YELLOW}An unencrypted backup drive is a readable copy of everything on this machine${NC}"
echo "— every file, every password store, every key in /etc — for anyone who picks"
echo "the drive up. The machine's own encryption does not extend to the backup."
echo ""
echo "You can encrypt it in place later, keeping the backups on it, with LinuxLocker:"
echo " https://github.com/doug445/LinuxLocker"
echo ""
ask "Type PLAIN to accept that risk and format without encryption, anything else to go back: "
if [ "$REPLY" = "PLAIN" ]; then PLAIN_DRIVE_ACCEPTED=1; return 0; fi
warn "Not accepted — nothing was written."
return 1
}
ask() { # ask PROMPT -> REPLY (trimmed)
echo -en "$1"
read -r REPLY
REPLY="${REPLY#"${REPLY%%[![:space:]]*}"}"; REPLY="${REPLY%"${REPLY##*[![:space:]]}"}"
}
wait_for_drive() {
WAITING_FOR_DRIVE=1
BACKUP_MOUNT="/mnt/backup"
echo ""
log "Installing the backup system now without a drive."
log "When the backup drive is connected, run: sudo ./deploy.sh"
log "It will find the drive (or walk you through setting it up) and finish the configuration."
echo ""
}
# A blank disk: no partition table, no filesystem, nothing on it in use. The
# thing a user has just unboxed and plugged in.
disk_is_blank() {
local dev="$1" pt fs
pt=$(lsblk -dno PTTYPE "$dev" 2>/dev/null || true); fs=$(lsblk -dno FSTYPE "$dev" 2>/dev/null || true)
[ -z "$pt" ] && [ -z "$fs" ] && [ "$(lsblk -rno NAME "$dev" 2>/dev/null | wc -l)" -le 1 ] && ! disk_in_use "$dev"
}
# Whole disks that are not in use: NAME SIZE TRAN HOTPLUG MODEL, one per line.
# Blank ones are marked; the first blank hotplug/USB disk is remembered in
# BLANK_DISK as the suggested default.
BLANK_DISK=""
list_candidate_disks() {
local line NAME SIZE TRAN HOTPLUG MODEL TYPE busy mark
BLANK_DISK=""
while IFS= read -r line; do
NAME=""; SIZE=""; TRAN=""; HOTPLUG=""; MODEL=""; TYPE=""
eval "$line" # lsblk -P emits NAME="..." pairs, quoted and escaped by lsblk itself
[ "$TYPE" = disk ] || continue
case "$NAME" in loop*|zram*|sr*|ram*|nbd*) continue ;;
esac
busy=""; mark=""
if disk_in_use "/dev/$NAME"; then busy=" <- in use, not eligible"
elif disk_is_blank "/dev/$NAME"; then
mark=" <- blank, ready to set up"
if [ -z "$BLANK_DISK" ] && { [ "$HOTPLUG" = 1 ] || [ "$TRAN" = usb ]; }; then BLANK_DISK="/dev/$NAME"; fi
fi
printf ' %-14s %8s %-6s %-8s %s%s%s\n' "/dev/$NAME" "$SIZE" "${TRAN:--}" "$([ "$HOTPLUG" = 1 ] && echo hotplug || echo fixed)" "${MODEL:-}" "$busy" "$mark"
done < <(lsblk -dPo NAME,SIZE,TRAN,HOTPLUG,MODEL,TYPE 2>/dev/null)
}
# Blank hotplug/USB disks present right now, one path per line (no prompt).
blank_hotplug_disks() {
local line NAME TRAN HOTPLUG TYPE
while IFS= read -r line; do
NAME=""; TRAN=""; HOTPLUG=""; TYPE=""
eval "$line"
[ "$TYPE" = disk ] || continue
case "$NAME" in loop*|zram*|sr*|ram*|nbd*) continue ;; esac
{ [ "$HOTPLUG" = 1 ] || [ "$TRAN" = usb ]; } || continue
disk_is_blank "/dev/$NAME" && echo "/dev/$NAME"
done < <(lsblk -dPo NAME,TRAN,HOTPLUG,TYPE 2>/dev/null)
# A non-blank last disk left the loop's status at 1; callers run under
# set -e -o pipefail and died there (an SD card listed last did it).
return 0
}
# On a host that already has a drive configured: a blank drive that has just
# been connected is worth mentioning, and on a terminal worth offering.
offer_blank_drive() {
local blanks
blanks=$(blank_hotplug_disks | tr '\n' ' ')
[ -n "$blanks" ] || return 0
log "New blank drive connected: ${blanks% }"
if (( DRY )) || [ ! -t 0 ]; then
log " (a real run on a terminal offers to set it up as the backup drive)"
return 0
fi
echo ""
echo "A blank drive is connected: ${blanks% }"
echo "Set it up as THIS host's backup drive? The current configuration ($BACKUP_MOUNT)"
echo "is replaced; the old config is kept beside the new one as .old-<date>."
ask "Set up the blank drive now? [y/N]: "
case "$REPLY" in y|Y|yes|YES)
if mountpoint -q "$BACKUP_MOUNT" 2>/dev/null; then
log "unmounting the current drive at $BACKUP_MOUNT first"
umount "$BACKUP_MOUNT" 2>/dev/null || { err "could not unmount $BACKUP_MOUNT (busy?) — leaving the current drive in place"; return 0; }
fi
WAITING_FOR_DRIVE=0
BACKUP_MOUNT=/mnt/backup
prepare_backup_drive "${blanks%% *}"
;;
esac
}
# A disk is in use if anything on it (partition, LUKS mapping, LV) is mounted
# or swapped, or if any of its UUIDs appear in fstab or crypttab.
disk_in_use() {
local dev="$1" u mp p
# MOUNTPOINTS arrived in util-linux 2.37; on Debian 11 / Ubuntu 20.04 /
# RHEL 8 the column is unknown, lsblk printed nothing, and the SYSTEM disk
# was listed as eligible. Fall back to MOUNTPOINT; an lsblk that fails
# outright means "in use" — never "free".
mp=$(lsblk -rno MOUNTPOINTS "$dev" 2>/dev/null) || mp=$(lsblk -rno MOUNTPOINT "$dev" 2>/dev/null) || return 0
grep -q . <<<"$mp" && return 0
while read -r p; do [ -n "$p" ] && grep -qs "^$p " /proc/swaps && return 0; done < <(lsblk -rnpo NAME "$dev" 2>/dev/null)
while read -r u; do
[ -n "$u" ] || continue
grep -qsF "$u" /etc/fstab /etc/crypttab && return 0
done < <(lsblk -rno UUID,PARTUUID "$dev" 2>/dev/null | tr ' ' '\n')
return 1
}
# The single typed confirmation before anything is written to a device.
confirm_erase() { # confirm_erase DEV DESCRIPTION
local dev="$1"
echo ""
echo -e "${RED}This will ERASE $dev${NC} ($2). Everything on it will be gone."
{ lsblk -o NAME,SIZE,FSTYPE,LABEL,MOUNTPOINTS "$dev" 2>/dev/null || lsblk -o NAME,SIZE,FSTYPE,LABEL,MOUNTPOINT "$dev" 2>/dev/null; } | sed 's/^/ /'
disk_in_use "$dev" && { err "$dev is IN USE (mounted, swap, or in fstab/crypttab) — refusing to erase it."; return 1; }
ask "Type the device path ($dev) to continue, anything else to abort: "
[ "$REPLY" = "$dev" ] || { warn "Aborted — nothing was written."; return 1; }
ask "Type ERASE to confirm: "
[ "$REPLY" = "ERASE" ] || { warn "Aborted — nothing was written."; return 1; }
return 0
}
# Partition a whole disk (GPT, one partition) and make btrfs on it. btrfs is
# used for the backup drive on every host: the send/receive replicas of a btrfs
# root need a btrfs destination, and compression is free space on the others.
drive_still_there() { # drive_still_there DEV — false (with a message) if it was unplugged
[ -b "$1" ] && return 0
err "$1 is gone — drive disconnected? Nothing further was written."
return 1
}
format_plain() { # format_plain DEV -> sets FORMATTED_PART
local dev="$1"
confirm_erase "$dev" "plain btrfs, label Borg-backup" || return 1
drive_still_there "$dev" || return 1
log "Wiping signatures and writing a GPT with one partition on $dev ..."
wipefs -a "$dev" >/dev/null
printf 'label: gpt\n,,L\n' | sfdisk --quiet --wipe always "$dev"
udevadm settle 2>/dev/null || sleep 2
drive_still_there "$dev" || return 1
FORMATTED_PART=$(lsblk -rnpo NAME,TYPE "$dev" | awk '$2=="part"{print $1; exit}' || true)
[ -n "$FORMATTED_PART" ] && [ -b "$FORMATTED_PART" ] || { err "partition did not appear on $dev"; return 1; }
log "mkfs.btrfs -L Borg-backup $FORMATTED_PART ..."
mkfs.btrfs -f -q -L Borg-backup "$FORMATTED_PART" || { err "mkfs.btrfs failed"; return 1; }
udevadm settle 2>/dev/null || sleep 1
return 0
}
# Enroll a keyfile in the LUKS drive so the attach unit can unlock it on
# connect. Needs the drive's passphrase once. Never touches the existing slots
# and never lowers the AF hash — luksAddKey without --hash silently writes
# sha256 into the new slot on some cryptsetup builds.
enroll_keyfile() { # enroll_keyfile LUKS_DEV
local ldev="$1" kdir=/etc/luks-keys kf=/etc/luks-keys/backup-drive.key
echo ""
echo "Unlock-on-connect: with a keyfile enrolled, plugging the drive in unlocks and"
echo "mounts it (never starts a backup). The keyfile lives at $kf, mode 0400, root only."
echo "Without it you will unlock the drive by hand before each backup."
ask "Enroll a keyfile now? [Y/n]: "
case "$REPLY" in n|N|no|NO) log "No keyfile enrolled — unlock by hand before backing up."; return 0 ;; esac
mkdir -p "$kdir"; chmod 700 "$kdir"
if [ ! -s "$kf" ]; then
( umask 077; head -c 64 /dev/urandom > "$kf" ) || { err "could not write $kf"; return 1; }
elif cryptsetup open --test-passphrase --key-file "$kf" "$ldev" 2>/dev/null; then
# Already enrolled: luksAddKey does not dedupe, and every re-run
# through this path burned another keyslot (LUKS1 has eight).
log "keyfile $kf already opens $ldev — nothing to enroll"
DRIVE_KEYFILE="$kf"
return 0
else
log "keyfile $kf exists but does not open $ldev — enrolling it"
fi
chmod 400 "$kf"
# LUKS1 (older GNOME Disks / GParted drives) accepts only pbkdf2; LUKS2
# gets argon2id with a memory cost a 1 GB Pi can still afford.
local kdf=()
if cryptsetup luksDump "$ldev" 2>/dev/null | grep -q '^Version:[[:space:]]*1'; then
kdf=(--hash sha512)
else
kdf=(--pbkdf argon2id --pbkdf-memory 262144 --hash sha512)
fi
echo "cryptsetup will ask for the drive's passphrase:"
if cryptsetup luksAddKey "${kdf[@]}" "$ldev" "$kf"; then
DRIVE_KEYFILE="$kf"
log "keyfile enrolled in $ldev"
else
warn "luksAddKey failed — no keyfile enrolled; you can retry with:"
warn " sudo cryptsetup luksAddKey ${kdf[*]} $ldev $kf"
# Never record a keyfile that does not open the drive: every plug-in
# would end in "luksOpen failed" and a failed unit.
rm -f "$kf"
fi
return 0
}
mount_backup_fs() { # mount_backup_fs FS_DEV
local fsdev="$1" fstype
drive_still_there "$fsdev" || return 1
fstype=$(lsblk -no FSTYPE "$fsdev" 2>/dev/null | head -1 || true)
mkdir -p "$BACKUP_MOUNT"
if [ "$fstype" = btrfs ]; then
mount -o compress=zstd:1 "$fsdev" "$BACKUP_MOUNT" || { err "mount failed"; return 1; }
else
mount "$fsdev" "$BACKUP_MOUNT" || { err "mount failed"; return 1; }
fi
chown "$SUDO_USER:" "$BACKUP_MOUNT" 2>/dev/null || true # primary group, whatever it is called (openSUSE: users)
log "mounted $fsdev ($fstype) at $BACKUP_MOUNT"
DRIVE_SETUP_DONE=1
return 0
}
prepare_backup_drive() { # prepare_backup_drive [PRESELECTED_DEV]
local preselect="${1:-}"
if [ -z "$preselect" ]; then
echo ""
echo "============================================"
echo " No backup drive is mounted"
echo "============================================"
echo ""
echo " 1) I have a drive connected — set it up now"
echo " 2) Wait — install the backup system now, set the drive up later"
echo ""
ask "Choice [1/2]: "
case "$REPLY" in 1) ;; *) wait_for_drive; return ;; esac
fi
local dev="" luks_part="" fs_part="" mapper="" inner_fs="" luks_uuid="" suggested=""
while :; do
echo ""
echo "Connect the backup drive now if it is not already. Whole disks seen:"
echo ""
list_candidate_disks
suggested="${preselect:-$BLANK_DISK}"
[ -n "$suggested" ] && [ -b "$suggested" ] || suggested=""
echo ""
echo " (r) rescan (w) wait — install now, set the drive up later"
ask "Device to use for backups${suggested:+ [$suggested]}: "
case "$REPLY" in
r|R) continue ;;
w|W) wait_for_drive; return ;;
"") [ -n "$suggested" ] && REPLY="$suggested" || { wait_for_drive; return; } ;;
esac
dev="$REPLY"
[ -b "$dev" ] || { warn "$dev is not a block device"; continue; }
if disk_in_use "$dev"; then
warn "$dev holds a mounted filesystem, active swap, or an fstab/crypttab entry — refusing to touch it."
continue
fi
# Big enough? The floor is one full copy of the sources plus spare
# room; below it the drive is refused outright. Below twice the system
# disk it is accepted with the recommendation stated.
dev_bytes=$(lsblk -dnbo SIZE "$dev" 2>/dev/null | head -1 || true)
if cap_msg=$(bx_check_backup_capacity "${dev_bytes:-0}"); then
case "$cap_msg" in *"OK but small"*) warn "$cap_msg" ;; *) log "$cap_msg" ;; esac
else
err "$cap_msg"
err "$dev is too small to be this machine's backup drive — pick another."
continue
fi
break
done
luks_part=$(lsblk -rnpo NAME,FSTYPE "$dev" | awk '$2=="crypto_LUKS"{print $1; exit}' || true)
# FSTYPE last: lsblk -r collapses an empty column, so with FSTYPE in the
# middle a disk with only a partition table read TYPE ("disk") as its fs.
fs_part=$(lsblk -rnpo NAME,TYPE,FSTYPE "$dev" | awk '$3!="" && $3!="crypto_LUKS" && $3!="swap"{print $1; exit}' || true)
# ----- A) already LUKS-encrypted: unlock and adopt -----------------------
if [ -n "$luks_part" ]; then
luks_uuid=$(cryptsetup luksUUID "$luks_part" 2>/dev/null || true)
mapper="luks-$luks_uuid"
log "$luks_part is LUKS-encrypted (UUID ${luks_uuid:-?})."
if [ ! -e "/dev/mapper/$mapper" ]; then
echo "cryptsetup will ask for its passphrase:"
cryptsetup open "$luks_part" "$mapper" || { err "could not unlock $luks_part"; wait_for_drive; return; }
fi
udevadm settle 2>/dev/null || sleep 1
inner_fs=$(lsblk -no FSTYPE "/dev/mapper/$mapper" 2>/dev/null | head -1 || true)
if [ -n "$inner_fs" ]; then
echo ""
echo "Inside it: a $inner_fs filesystem (label: $(lsblk -no LABEL "/dev/mapper/$mapper" 2>/dev/null | head -1))."
echo " 1) Use it as-is — keep whatever is on it, add backups alongside"
echo " 2) Reformat the inside as btrfs (label Borg-backup) — erases it"
ask "Choice [1/2]: "
if [ "$REPLY" = 2 ]; then
confirm_erase "/dev/mapper/$mapper" "inside of the LUKS container, btrfs" || { wait_for_drive; return; }
drive_still_there "$luks_part" || { wait_for_drive; return; }
mkfs.btrfs -f -q -L Borg-backup "/dev/mapper/$mapper" || { err "mkfs.btrfs failed"; wait_for_drive; return; }
udevadm settle 2>/dev/null || sleep 1
fi
else
echo "The container is empty inside."
confirm_erase "/dev/mapper/$mapper" "inside of the LUKS container, btrfs" || { wait_for_drive; return; }
mkfs.btrfs -f -q -L Borg-backup "/dev/mapper/$mapper" || { err "mkfs.btrfs failed"; wait_for_drive; return; }
udevadm settle 2>/dev/null || sleep 1
fi
enroll_keyfile "$luks_part"
mount_backup_fs "/dev/mapper/$mapper" || { wait_for_drive; return; }
return
fi
# ----- B) plain filesystem present: adopt or reformat ---------------------
if [ -n "$fs_part" ]; then
echo ""
echo "$fs_part already has a $(lsblk -no FSTYPE "$fs_part" | head -1) filesystem (label: $(lsblk -no LABEL "$fs_part" | head -1))."
echo " 1) Use it as-is — keep whatever is on it, add backups alongside"
echo " 2) Erase and format the whole drive for backups (plain btrfs)"
echo " 3) Encrypt it first — I will do that myself, then re-run deploy.sh"
echo " 4) Wait — install now, set the drive up later"
ask "Choice [1-4]: "
case "$REPLY" in
1) accept_plain_risk || { explain_encrypt_first "$dev"; wait_for_drive; return; }
mount_backup_fs "$fs_part" || wait_for_drive; return ;;
2) ;;
3) explain_encrypt_first "$dev"; wait_for_drive; return ;;
*) wait_for_drive; return ;;
esac
else
# ----- C) empty drive --------------------------------------------------
echo ""
echo "$dev has no filesystem."
echo " 1) Encrypt it first — I will do that myself, then re-run deploy.sh (recommended)"
echo " 2) Format it plain now (btrfs, label Borg-backup); encrypt in place later if wanted"
echo " 3) Wait — install now, set the drive up later"
ask "Choice [1-3]: "
case "$REPLY" in
1) explain_encrypt_first "$dev"; wait_for_drive; return ;;
2) ;;
*) wait_for_drive; return ;;
esac
fi
accept_plain_risk || { explain_encrypt_first "$dev"; wait_for_drive; return; }
format_plain "$dev" || { wait_for_drive; return; }
echo ""
echo "Formatted, unencrypted. To encrypt this drive in place later, keeping the backups on it:"
echo " LinuxLocker — https://github.com/doug445/LinuxLocker (in-place LUKS2, data partitions included)"
echo "then re-run deploy.sh so the config picks up the LUKS UUID and unlock-on-connect."
mount_backup_fs "$FORMATTED_PART" || wait_for_drive
}
explain_encrypt_first() {
local dev="$1"
echo ""
echo "Encrypt $dev yourself, then come back — deploy.sh will find the LUKS drive,"
echo "ask for its passphrase once, offer to enroll a keyfile for unlock-on-connect,"
echo "and adopt it. Any of these does the job:"
echo ""
echo " GNOME Disks Format Disk (GPT) -> + partition -> type: Internal disk (ext4/btrfs),"
echo " tick 'Password protect volume (LUKS)', filesystem btrfs, label Borg-backup"
echo " GParted Device > Create Partition Table (gpt); Partition > New, btrfs, tick 'Encrypt with LUKS'"
local p1; p1=$(lsblk -rnpo NAME,TYPE "$dev" 2>/dev/null | awk '$2=="part"{print $1; exit}' || true)
if [ -z "$p1" ]; then case "$dev" in *[0-9]) p1="${dev}p1" ;; *) p1="${dev}1" ;; esac; fi # nvme0n1p1, mmcblk0p1, sdb1
echo " Command line sudo cryptsetup luksFormat --type luks2 --pbkdf argon2id $p1"
echo " sudo cryptsetup open $p1 backup && sudo mkfs.btrfs -L Borg-backup /dev/mapper/backup"
echo ""
echo "Prefer to keep a plain drive for now? Format it here instead, and encrypt it in place"
echo "later with LinuxLocker: https://github.com/doug445/LinuxLocker"
echo ""
echo "When the drive is ready and connected: sudo ./deploy.sh"
}
###############################################################################
# Check if borg is already deployed and working
###############################################################################
# Only a borg setup that is NOT this suite's is preserved: the suite's own
# borg-backup.sh sources backup-common.sh, which every deploy upgrades, so an
# older copy of it is upgraded with it. A hand-written one is kept (FORCE_BORG=1
# replaces it, keeping it as borg-backup.sh.pre-suite-<stamp>) — and said to
# be foreign: it reads none of /etc/backup-system.conf (a pre-suite script
# still backed up to /run/media/will/Borg-backup after the drive had moved).
BORG_FOREIGN=false
detect_existing_borg() {
BORG_ALREADY_DEPLOYED=false
[ -f /usr/local/sbin/borg-backup.sh ] || return 0
grep -q 'backup-common\.sh' /usr/local/sbin/borg-backup.sh 2>/dev/null && return 0
BORG_FOREIGN=true
if [ -f /etc/systemd/system/borg-backup.service ] && \
[ -f /etc/systemd/system/borg-backup.timer ] && \
systemctl is-active borg-backup.timer &>/dev/null; then
BORG_ALREADY_DEPLOYED=true
fi
}
###############################################################################
# Convert mount path to systemd unit name (for RequiresMountsFor)
###############################################################################
systemd_escape_path() {
# systemd-escape handles this properly
systemd-escape --path "$1" 2>/dev/null || echo "$1" | sed 's|^/||;s|/|-|g'
}
###############################################################################
# Generate BIT config for this system
###############################################################################
generate_bit_config() {
local user_to_exclude="$SUDO_USER"
local exclude_idx=19
local exclude_size=18 # base excludes (1-18)
# BX_BIT_CONFIG: the fixture test writes a scratch config instead of root's.
local cfg="${BX_BIT_CONFIG:-/root/.config/backintime/config}"
# An existing config is the user's — it may carry hand-tuned exclusions or
# rsync options — and is never regenerated over, except when a new drive
# was set up this run (the destination path changed); then the old one is
# kept beside it.
if [ -f "$cfg" ] && [ "$DRIVE_SETUP_DONE" != 1 ]; then
# Two lines are not the user's to keep: the destination must be this
# host's backup drive (a drive moved from /mnt/borg-backup to
# /mnt/backup left the GUI, and the config copied into every snapshot,
# pointing at the old path), and Back In Time's own scheduler must stay
# off — with it on, `backintime check-config` below installs a crontab
# that runs BIT by AGE behind the suite's back.
local want="$BACKUP_MOUNT/backintime" have changed=""
have=$(sed -n 's/^profile1\.snapshots\.path=//p' "$cfg" | head -1)
if [ "$have" != "$want" ]; then
if grep -q '^profile1\.snapshots\.path=' "$cfg"; then
sed -i "s#^profile1\.snapshots\.path=.*#profile1.snapshots.path=$want#" "$cfg"
else
printf 'profile1.snapshots.path=%s\n' "$want" >> "$cfg"
fi
changed="snapshots.path ${have:-<unset>} -> $want"
fi
if [ "$(sed -n 's/^profile1\.schedule\.mode=//p' "$cfg" | head -1)" != 0 ]; then
if grep -q '^profile1\.schedule\.mode=' "$cfg"; then
sed -i 's/^profile1\.schedule\.mode=.*/profile1.schedule.mode=0/' "$cfg"
else
printf 'profile1.schedule.mode=0\n' >> "$cfg"
fi
changed="${changed:+$changed; }schedule.mode -> 0 (the suite runs BIT, never BIT's own cron)"
fi
if [ -n "$changed" ]; then
log " $cfg exists — kept; updated: $changed"
else
log " $cfg exists — left as-is"
fi
return 1
fi
if [ -f "$cfg" ]; then
/usr/bin/cp -a "$cfg" "$cfg.old-$(date +%Y%m%d-%H%M%S)"
log " new drive this run — previous BIT config kept as $cfg.old-*"
fi
# SELinux hosts: rsync must not carry security.selinux xattrs into the
# snapshot tree, or every file restores with the label it had at backup
# time and the target relabels on first boot (or refuses to).
local rsync_en=false rsync_val=""
if [ -d /sys/fs/selinux ]; then
rsync_en=true; rsync_val="--filter='-x security.selinux'"
fi
# Start with base config
cat > "$cfg" << EOF
config.version=6
profile1.name=Full System Backup
# Snapshot destination
profile1.snapshots.path=$BACKUP_MOUNT/backintime