-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBackup.sh
More file actions
executable file
·2093 lines (1817 loc) · 89 KB
/
Backup.sh
File metadata and controls
executable file
·2093 lines (1817 loc) · 89 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
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# ---------------------------------------------------------------------------------------------------------------
# Backup_pi - Raspberry Pi image and user backup script using image-backup and PiShrink
# Location: /usr/local/bin/Backup.sh (Symlinked to ~/Installs/Backup_pi/Backup.sh)
# (sudo ln -s /user/pi/Installs/Backup_pi/Backup.sh /usr/local/bin/Backup.sh )
# Scheduled: 23:59 Daily via /etc/crontab
# (sudo nano /etc/crontab )
# (ADD: 59 23 * * * root /bin/bash /usr/local/bin/Backup.sh >> /var/log/Backup_pi.log 2>&1 )
# ( You might need to create the Backup_pi.log file first...)
#
# FIX:
#
# # MARKER_FILE COULD BE: "$BACKUP_ROOT/.BACKUP_IS_HERE"
#
# ----------------------------------------------------------------------------------------------------------------
# Set for true exit code when using piped commands
set -o pipefail
# Check if run as sudo or re-start it if it was not
if [[ $EUID -ne 0 ]]; then
echo "Elevating privileges..."
exec sudo -E "$0" "$@"
fi
# Arrays to keep track of different mount types
FSTAB_MOUNTS=()
MANUAL_MOUNTS=()
MANUAL_PATHS=() # New array for clean paths
# The Flags: starts as "false"
DRIVES_ARE_UNMOUNTED=false
SERVICES_STOPPED=false
DOCKER_CONTAINERS_STOPPED=false
check_commands() {
local MISSING=0
# Loop through every command name you pass to the function
for cmd_input in "$@"; do
local IS_OPTIONAL=0
local cmd="$cmd_input"
# 1. Check if it starts with '?' (Our "Optional" marker)
if [[ "$cmd" == "?"* ]]; then
IS_OPTIONAL=1
cmd="${cmd#?}" # Strip the '?' for the actual check
fi
local path
path=$(command -v "$cmd")
if [[ -n "$path" ]]; then
# 2. Create the variable (e.g., PISHRINK_BIN)
local var_name
var_name=$(echo "${cmd%.*}" | tr '[:lower:]' '[:upper:]' | tr '-' '_')_BIN
declare -g "$var_name"="$path"
else
if [[ "$IS_OPTIONAL" -eq 1 ]]; then
echo "Notice: Optional tool '$cmd' not found. Disabling feature." | do_log
else
# echo "CRITICAL: Required tool '$cmd' not found!" | do_log
# exit 1 # Hard stop only for required tools
echo "Error: Required command '$cmd' not found in PATH." | do_log
MISSING=$((MISSING + 1))
fi
fi
done
# If any mission-critical commands are missing, you might want to exit
if (( MISSING > 0 )); then
echo "Total missing commands: $MISSING. Please install them." | do_log
exit 1 # Optional: Uncomment to stop the script if tools are missing
fi
}
# OS codename - used for backup filename and folder structure
get_codename() {
local VERSION_CODENAME
VERSION_CODENAME=$(bash -c '. /etc/os-release; echo $VERSION_CODENAME' | sed 's/.*/\u&/')
echo "$VERSION_CODENAME"
}
# Ensure log folder structure exists, try to create it
log_directory_check() {
echo "Checking for log directory: ${LOG_TO_FILE_DIRECTORY} and creating if missing"
[ ! -d "$LOG_TO_FILE_DIRECTORY" ] && mkdir -p "$LOG_TO_FILE_DIRECTORY"
echo ""
}
# Check if external log file is enabled and if so tee to that file (and std output also)
do_log() {
# Combine them here once to ensure the path is clean
local LOG_PATH="${LOG_TO_FILE_DIRECTORY}/${LOG_TO_FILE_FILENAME}"
# if [ "$LOG_TO_FILE" == "1" ] && [ -d "$(dirname "$LOG_PATH")" ]; then
# if [[ "$LOG_TO_FILE" == "1" ]] && [[ -n "$LOG_PATH" ]] && [[ ! -d "$LOG_PATH" ]] && [[ -d "$(dirname "$LOG_PATH")" ]]; then
# 1. Is logging enabled?
# 2. Is the path set?
# 3. Does it NOT end in a slash? (Meaning it's a file, not a folder)
# 4. Does the parent folder actually exist?
if [[ "$LOG_TO_FILE" == "1" ]] && \
[[ -n "$LOG_PATH" ]] && \
[[ "$LOG_PATH" != */ ]] && \
[[ -d "$(dirname "$LOG_PATH")" ]]; then
tee -a "$LOG_PATH"
else
cat # Just passes the text through without saving to a file
fi
}
# Ensure backup folder structure exists, try to create it
directory_check() {
echo "Checking for backup directory: ${BACKUP_PATH} and creating if missing" | do_log
echo "" | do_log
[ ! -d "$BACKUP_PATH" ] && mkdir -p "$BACKUP_PATH"
}
# 1. FIND AND ANALYZE THE CUSTOM MOUNTS
find_custom_mounts() {
echo "Checking for custom mounts..." | do_log
# Get the array of mounts not part of the OS (using excluded folders)
local targets=()
# 1. Use mapfile -t to read line-by-line
# 2. Skip the -0 and -z flags
mapfile -t targets < <(findmnt --real -nlo TARGET | \
grep -vE "^/(boot|media|mnt|srv|opt|var|dev|proc|sys)?(/|$)")
# targets=$(findmnt --real -nlo TARGET | grep -vE "^/(boot|media|mnt|srv|opt|var|dev|proc|sys)?(/|$)")
# local targets=$(findmnt --real -nlo TARGET | grep -vE "^/(boot|media|mnt|srv|opt|var|dev|proc|sys)?(/|$)")
# if [ -z "$targets" ]; then
if [ "${#targets[@]}" -eq 0 ]; then
echo "No custom mounts found." | do_log
echo "" | do_log
return
fi
# for mnt in $targets; do
for mnt in "${targets[@]}"; do
# Check if the mount exists in fstab
if findmnt --fstab --target "$mnt" >/dev/null 2>&1; then
FSTAB_MOUNTS+=("$mnt")
echo "Found fstab mount: $mnt" | do_log
else # Not in fstab! Save its live mount command details
# FIRST ENSURE THE .smbcredentials file exists
# Define the expected path to the credentials file
CREDS_FILE="$SCRIPT_DIR/.smbcredentials"
# Verify the file exists and is not empty
if [[ ! -f "$CREDS_FILE" ]]; then
echo "❌ ERROR: Credentials file missing at $CREDS_FILE" | do_log
exit 1
elif [[ ! -s "$CREDS_FILE" ]]; then
echo "❌ ERROR: Credentials file at $CREDS_FILE is empty" | do_log
exit 1
fi
# echo "✅ Credentials file verified."
# We need: Source (device), FSType, and Options
local src
local typ
local opt
src=$(findmnt -nlo SOURCE "$mnt")
typ=$(findmnt -nlo FSTYPE "$mnt")
opt=$(findmnt -nlo OPTIONS "$mnt")
# Re-inject credentials for CIFS
if [[ "$typ" == "cifs" ]]; then
# Clean up potential duplicate 'user' tags findmnt might show
# This catches 'user=' OR 'username='
opt=$(echo "$opt" | sed -E 's/user(name)?=[^,]*//g; s/password=[^,]*//g; s/,,/,/g')
# # Finds the home directory of the person who typed 'sudo'
# local real_home
# real_home=$(getent passwd "$SUDO_USER" | cut -d: -f6)
# opt="credentials=${real_home:-$HOME}/.smbcredentials,$opt"
# opt="credentials=$HOME/.smbcredentials,$opt"
# SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)
opt="credentials=$SCRIPT_DIR/.smbcredentials,$opt"
fi
# MANUAL_MOUNTS+=("sudo mount -t $typ -o \"$opt\" \"$src\" \"$mnt\"") # "$mnt|$info")
MANUAL_MOUNTS+=("sudo mount -t $typ -o \"$opt\" \"$src\" \"$mnt\"")
MANUAL_PATHS+=("$mnt") # Save the clean path here
echo "Found custom mount: $mnt with Source: $src Type: $typ Options: $opt" | do_log
fi
echo "" | do_log
done
}
# 2. UNMOUNT FUNCTION
unmount_custom_mounts() {
for mnt in "${FSTAB_MOUNTS[@]}"; do
DRIVES_ARE_UNMOUNTED=true
echo "Attempting to unmount $mnt..." | do_log
# timeout 10s: If it's busy, it stops trying after 10 seconds
# sudo umount -l: "Lazy" unmount detaches it now, cleans up later
if sudo timeout 10s umount -l "$mnt"; then
echo "Successfully detached fstab mount: $mnt" | do_log
else
echo "Warning: $mnt is very busy. Lazy unmount initiated." | do_log
fi
# Give the system a split second to settle
sleep 1
# Check if the folder is empty
if [ -z "$(ls -A "$mnt" 2>/dev/null)" ]; then
echo "✅ Confirmed: $mnt is empty and unmounted." | do_log
DRIVES_ARE_UNMOUNTED=true
else
echo "⚠️ ALERT: $mnt STILL HAS FILES!" | do_log
echo "These might be 'ghost files' sitting on your SD card." | do_log
echo "" | do_log
# Optional: exit 1 <-- You could stop the backup here for safety
fi
# We successfully (or lazily) unmounted at least one drive
DRIVES_ARE_UNMOUNTED=true
done
# Extract the mount point (the last 'word') from each command in the array
# for cmd in "${MANUAL_MOUNTS[@]}"; do
# Use the index to keep the command and path synced
for i in "${!MANUAL_PATHS[@]}"; do
local mnt="${MANUAL_PATHS[$i]}"
local cmd="${MANUAL_MOUNTS[$i]}"
DRIVES_ARE_UNMOUNTED=true
# This grabs the last argument of the saved command
# local mnt=$(echo "$cmd" | awk '{print $NF}' | tr -d '"')
# Bulletproof Move 2: Space-safe way to get the mount point
# Instead of awk, we extract it from the command we just built
# local mnt=$(echo "$cmd" | grep -oP '(?<=" )/[^"]+(?=")')
# If the regex is too complex, just use the 'mnt' you had during the find phase
echo "Attempting to unmount $mnt..." | do_log
# timeout 10s: If it's busy, it stops trying after 10 seconds
# sudo umount -l: "Lazy" unmount detaches it now, cleans up later
if sudo timeout 10s umount -l "$mnt"; then
echo "Successfully detached manual mount: $mnt" | do_log
else
echo "Warning: $mnt is very busy. Lazy unmount initiated." | do_log
fi
# Give the system a split second to settle
sleep 1
# Check if the folder is empty
# if [ -z "$(ls -A "$mnt" 2>/dev/null)" ]; then
# Bulletproof Move 3: Sudo check for ghost files
if [ -z "$(sudo ls -A "$mnt" 2>/dev/null)" ]; then
echo "✅ Confirmed: $mnt is empty and unmounted." | do_log
DRIVES_ARE_UNMOUNTED=true
else
echo "⚠️ ALERT: $mnt STILL HAS FILES!" | do_log
echo "These might be 'ghost files' sitting on your SD card." | do_log
# Optional: exit 1 <-- You could stop the backup here for safety
fi
# We successfully (or lazily) unmounted at least one drive
DRIVES_ARE_UNMOUNTED=true
echo "" | do_log
done
}
# 3. RE-MOUNT
remount_custom_mounts() {
# A. Remount everything from fstab (simple)
echo "Restoring fstab mounts..." | do_log
sudo mount -a
echo "" | do_log
# B. Manually remount the ones that weren't in fstab
if [ ${#MANUAL_MOUNTS[@]} -eq 0 ]; then
echo "No manual mounts to restore." | do_log
echo "" | do_log
DRIVES_ARE_UNMOUNTED=false
return
fi
echo "" | do_log
echo "Restoring mounts from memory..."
for cmd in "${MANUAL_MOUNTS[@]}"; do
echo "Running: $cmd" | do_log
eval "$cmd"
# Grab the mount point from the end of the command
local mnt
mnt=$(echo "$cmd" | awk '{print $NF}' | tr -d '"')
# VERIFICATION: Check if the directory is readable and NOT empty
# (ls -A returns true if there is at least one file/folder inside)
if [ -d "$mnt" ] && [ "$(sudo ls -A "$mnt")" ]; then
echo "✅ Verified: $mnt is back online." | do_log
else
echo "⚠️ Warning: $mnt appears empty. Remount might have failed." | do_log
fi
echo "" | do_log
done
DRIVES_ARE_UNMOUNTED=false
}
# This function runs automatically when the script finishes or is interrupted (Ctrl+C)
cleanup() {
# Only run the remount if the flag was switched to "true"
if [ "$DRIVES_ARE_UNMOUNTED" = true ]; then
echo "Script finished or interrupted. Ensuring drives are remounted..." | do_log
remount_custom_mounts
else
echo "Cleanup: No unmounted drives to restore." | do_log
echo "" | do_log
fi
if [ "$SERVICES_STOPPED" = true ] || [ "$DOCKER_CONTAINERS_STOPPED" = true ]; then
startServices
fi
}
# Triggers on Exit, Ctrl+C (INT), and Terminal closure (TERM)
trap cleanup EXIT INT TERM
# Send messages as set in config
send_messages() {
# $1 is the first thing you pass to the function (your message)
local MSG="$1"
# 1. Telegram Logic
if [[ "$SEND_TELEGRAM_MESSAGES" == "1" && ( -n "$TELEGRAM_SEND_GROUP_TOPIC_BIN" || -n "$TELEGRAM_SEND_BIN" ) ]]; then
if [[ -n "$TELEGRAM_SEND_GROUP_TOPIC_BIN" ]]; then
# Use "5" as your default topic ID since it's hardcoded in your example
"$TELEGRAM_SEND_GROUP_TOPIC_BIN" "$MSG" "5" | do_log
else
"$TELEGRAM_SEND_BIN" "$MSG" | do_log
fi
fi
# 2. Gotify Logic
if [[ "$SEND_GOTIFY_MESSAGES" == "1" && -n "$GOTIFY_SEND_BIN" ]]; then
# Uses your sourced title and priority variables
"$GOTIFY_SEND_BIN" "$GOTIFY_MESSAGE_TITLE" "$MSG" "$GOTIFY_MESSAGE_PRIORITY" | do_log
fi
# 2. Ntfy Logic
if [[ "$SEND_NTFY_MESSAGES" == "1" && -n "$NTFY_SEND_BIN" ]]; then
# Uses your sourced title and priority variables
"$NTFY_SEND_BIN" "$MSG" "$SEND_NTFY_TOPIC" | do_log
fi
}
send_log_messages() {
# 1. First, check the Master "Send Logs" Switch
[[ "$SEND_LOG_MESSAGES" != "1" ]] && return 0
local TITLE="Backup Log from $HOSTNAME"
local LINE_COUNT
LINE_COUNT=$(wc -l < "$FULL_LOG_PATH")
# 2. Telegram: Send the actual FILE
if [[ "$SEND_TELEGRAM_MESSAGES" == "1" && ( -n "$TELEGRAM_SEND_GROUP_TOPIC_FILE_BIN" || -n "$TELEGRAM_SEND_BIN" ) ]]; then
if [[ -n "$TELEGRAM_SEND_GROUP_TOPIC_FILE_BIN" ]]; then
"$TELEGRAM_SEND_GROUP_TOPIC_FILE_BIN" "$TITLE" "5" "$FULL_LOG_PATH" | do_log
else
"$TELEGRAM_SEND_BIN" --file "$FULL_LOG_PATH" --caption "$TITLE"
fi
fi
# 3. Gotify: Send the FORMATTED SNIPPET (If log is more than 200 lines)
if [[ "$SEND_GOTIFY_MESSAGES" == "1" && -n "$GOTIFY_SEND_BIN" ]]; then
local GOTIFY_MSG
if [[ "$LINE_COUNT" -le 200 ]]; then
# File is short: send the whole thing
GOTIFY_MSG=$(cat "$FULL_LOG_PATH")
else
local START_LOG
local END_LOG
START_LOG=$(head -n 100 "$FULL_LOG_PATH")
END_LOG=$(tail -n 100 "$FULL_LOG_PATH")
# SNIPPET=$(printf -- "--- FIRST 100 LINES ---\n%s\n\n--- [... SNIP ...] ---\n\n--- LAST 100 LINES ---\n%s" "$START_LOG" "$END_LOG")
GOTIFY_MSG=$(printf -- "--- FIRST 100 LINES ---\n%s\n\n--- [... SNIP ...] ---\n\n--- LAST 100 LINES ---\n%s" "$START_LOG" "$END_LOG")
fi
"$GOTIFY_SEND_BIN" "$GOTIFY_MESSAGE_TITLE" "$GOTIFY_MSG" "$GOTIFY_MESSAGE_PRIORITY" | do_log
fi
# 4. Nfty: Send the actual FILE
if [[ "$SEND_NTFY_MESSAGES" == "1" && -n "$NTFY_SEND_FILE_BIN" ]]; then
"$NTFY_SEND_FILE_BIN" "$TITLE" "$SEND_NTFY_TOPIC" "$FULL_LOG_PATH" | do_log
fi
}
stopServices() {
if [[ "$STOP_CONTAINERS" == "0" && "$STOP_SERVICES" == "0" ]]; then
return 0
fi
echo "Stopping Docker containers and services before backup..." | do_log
echo | do_log
if [[ "$STOP_CONTAINERS" == "1" ]]; then
# Check if the variable is NOT blank before starting
if [[ -n "$DOCKER_CONTAINERS" ]]; then
echo "Stopping containers: $DOCKER_CONTAINERS" | do_log
# Loop through each item in the space-separated string
for container in $DOCKER_CONTAINERS; do
echo "Processing: $container..." | do_log
docker stop "$container" >/dev/null
DOCKER_CONTAINERS_STOPPED=true
done
echo "All containers specified to be stopped have been processed." | do_log
echo | do_log
else
echo "Error: DOCKER_CONTAINERS is empty or not defined." | do_log
echo | do_log
fi
fi
if [[ "$STOP_SERVICES" == "1" ]]; then
# Check if the variable is NOT blank before starting
if [[ -n "$SERVICES_RUNNING" ]]; then
echo "Stopping Services: $SERVICES_RUNNING" | do_log
# Loop through each item in the space-separated string
for services in $SERVICES_RUNNING; do
echo "Processing: $services..." | do_log
systemctl stop "$services" | do_log
SERVICES_STOPPED=true
done
echo "All services specified to be stopped have been processed." | do_log
echo | do_log
else
echo "Error: SERVICES_RUNNING is empty or not defined." | do_log
echo | do_log
fi
fi
sync
}
startServices() {
if [[ "$STOP_CONTAINERS" == "0" && "$STOP_SERVICES" == "0" ]]; then
return 0
fi
echo "Starting the stopped services and Docker containers..." | do_log
echo | do_log
# 1. Convert the strings into a temporary array
# shellcheck disable=SC2206
services=($SERVICES_RUNNING)
# shellcheck disable=SC2206
containers=($DOCKER_CONTAINERS)
if [[ "$STOP_SERVICES" == "1" ]]; then
# Check if the variable is NOT blank before starting
if [[ -n "$SERVICES_RUNNING" ]]; then
echo "Re-starting Services: $SERVICES_RUNNING" | do_log
# 2. Loop through the array indices in reverse
# Starting at (total length - 1) down to 0
for ((i = ${#services[@]} - 1; i >= 0; i--)); do
service="${services[$i]}"
echo "Starting: $service" | do_log
systemctl start "$service" | do_log
done
SERVICES_STOPPED=false
echo "All services stopped prior to the backup have been restarted." | do_log
echo | do_log
else
echo "Error: SERVICES_RUNNING is empty or not defined." | do_log
echo | do_log
fi
fi
if [[ "$STOP_CONTAINERS" == "1" ]]; then
# Check if the variable is NOT blank before starting
if [[ -n "$DOCKER_CONTAINERS" ]]; then
echo "Starting containers: $DOCKER_CONTAINERS" | do_log
# 2. Loop through the array indices in reverse
# Starting at (total length - 1) down to 0
for ((i = ${#containers[@]} - 1; i >= 0; i--)); do
container="${containers[$i]}"
echo "Starting: $container" | do_log
docker start "$container" >/dev/null
done
DOCKER_CONTAINERS_STOPPED=false
echo "All containers specified to be stopped have been restarted." | do_log
# echo | do_log
else
echo "Error: DOCKER_CONTAINERS is empty or not defined." | do_log
fi
fi
echo | do_log
}
# Find latest .img file in currenly defined backup path
find_incremental_file() {
local LATEST_INCREMENTAL
# 1. First, check if the backup drive/path is even mounted
# Look for marker file existence - means backup destination is available
# if [ ! -f "$MARKER_FILE" ]; then
# echo "ERROR: Marker file $MARKER_FILE not found! The backup drive might be unmounted. Aborting to save SD card space." >&2 # | do_log
# # echo "" | do_log
# # # send error notifications
# send_messages "❌ Backup FAILED for $HOSTNAME. BACKUP DRIVE NOT FOUND. Check Backup_pi.log"
# send_log_messages
# exit 1
# fi
LATEST_INCREMENTAL=$(bash -c "find ${BACKUP_PATH}/${HOSTNAME}-${OS_NAME}-${ARCHITECTURE}-*.img -type f 2>/dev/null | sort -n | cut -d ' ' -f 2- | tail -n 1")
if [[ -z "$LATEST_INCREMENTAL" ]]; then
echo "Incremental backup selected but no existing image file found to update... Terminating." >&2 | do_log
exit 1
fi
LATEST_INCREMENTAL_FILENAME=$(basename "$LATEST_INCREMENTAL") # or: filename="${src_file##*/}" (faster)
echo "$LATEST_INCREMENTAL_FILENAME"
}
check_space_for_backup() {
# 1. Get used space in KB for / and /boot (the two main partitions)
# --output=used provides just the column we need, tail -n +2 skips the header
ROOT_USED=$(df -k / --output=used | tail -n 1)
# BOOT_USED=$(df -k /boot/firmware --output=used | tail -n 1 2>/dev/null || df -k /boot --output=used | tail -n 1)
if [ -d "/boot/firmware" ]; then
BOOT_PATH="/boot/firmware"
else
BOOT_PATH="/boot"
fi
BOOT_USED=$(df -k "$BOOT_PATH" --output=used | tail -n 1)
# 2. Add them together
TOTAL_USED_KB=$((ROOT_USED + BOOT_USED))
# 3. Calculate estimate (120% of total) and convert to MB
# We multiply by 120 then divide by 100 to handle the percentage in integer math
ESTIMATE_KB=$((TOTAL_USED_KB * 120 / 100))
# ESTIMATE_MB=$((ESTIMATE_KB / 1024))
}
# --- Function to scrub CSV strings to remove progress options for CRON jobs (e.g. "--progress,--stats,--exclude") ---
scrub_csv() {
local input=$1
local IFS=','
local -a parts
read -ra parts <<<"$input"
local -a kept=()
for part in "${parts[@]}"; do
# Skip if it contains "progress"
[[ "$part" == *progress* ]] && continue
kept+=("$part")
done
# Join back with commas and echo
echo "$(
IFS=,
echo "${kept[*]}"
)"
}
rotate_backups_and_logs() {
local PATTERN="$1"
local LIMIT="$2"
local DESC="$3"
# 1. Get the list of all matches, sorted alphabetically (Oldest at top)
local ALL_BACKUPS
# shellcheck disable=SC2012
ALL_BACKUPS=$(ls -1d "${PATTERN}"* 2>/dev/null | sort)
# 2. Count them (ignoring empty results)
local TOTAL_FILES
TOTAL_FILES=$(echo "$ALL_BACKUPS" | grep -vc '^$')
if (( TOTAL_FILES > LIMIT )); then
local NUM_TO_DELETE=$(( TOTAL_FILES - LIMIT ))
local PURGE_LIST
PURGE_LIST=$(echo "$ALL_BACKUPS" | head -n "$NUM_TO_DELETE")
echo "Rotation ($DESC): Found $TOTAL_FILES. Keeping $LIMIT newest." | do_log
echo "$PURGE_LIST" | while read -r item; do
echo " - Removing: $item" | do_log
rm -rf -- "$item" 2>&1 | do_log
done
else
echo "Rotation ($DESC): Nominal. No purges required." | do_log
fi
}
# Get the directory where the script is located
SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
CONFIG_FILE="$SCRIPT_DIR/Backup.conf"
# Check if the config file exists before trying to load it
if [[ -f "$CONFIG_FILE" ]]; then
# The dot (.) is the command for 'source'
# shellcheck source=/dev/null
. "$CONFIG_FILE"
else
echo "ERROR: Configuration file $CONFIG_FILE not found!" | do_log
exit 1
fi
# Convert the IMAGE_BACKUP_OPTIONS string from the config into a real Bash array
read -r -a IMAGE_BACKUP_OPTIONS_ARRAY <<<"$IMAGE_BACKUP_OPTIONS"
# SETTINGS IN Backup.conf :
# Type can be - "image" / "image incremental" / "user" / "user compressed"
# BACKUP_TYPE="image incremental"
# BACKUP_ROOT="/media/usb0/Backups/
# MARKER_FILE="/media/usb0/Backups/.USB_IS_HERE"
# LOG_TO_FILE=1
# LOG_TO_FILE_DIRECTORY="/home/pi/Installs/Backup_pi/log"
# --- Mounts can be unmounted prior to backup (then re-mounted after)
# UNMOUNT_CUSTOM_MOUNTS_PRIOR_TO_BACKUP=0
# --- Services and Docker containers to stop & re-start
# STOP_SERVICES=1
# STOP_CONTAINERS=1
# A space-separated list of container names or IDs
# DOCKER_CONTAINERS="netdata pihole dnscrypt-proxy portainer"
# A space-separated list of Services
# SERVICES_RUNNING="smbd docker.socket docker tailscaled"
# --- Messaging options ---
# SEND_TELEGRAM_MESSAGES=1
# SEND_GOTIFY_MESSAGES=1
# SEND_NTFY_MESSAGES=1
# SEND_NTFY_TOPIC="TTsPlaceSF-host01-status"
# SEND_MESSAGES_ONLY_ON_ERROR=0
# SEND_CONFIRMATON_MESSAGE_ONLY=0
# SEND_LOG_MESSAGES=1
# --- Limits & Retention ---
# BACKUP_ANTAL=7
# USER_BACKUP_ANTAL=30
# LOG_ANTAL=30
# --- Backup "image-backup" & (-o rsync,options) ---
# IMAGE_BACKUP_OPTIONS="-n -o --info=progress2,--stats"
# IMAGE_BACKUP_INITIAL_IMAGE_SIZE=
# IMAGE_BACKUP_ADDITIONAL_IMAGE_SPACE_FOR_INCREMENTAL_BACKUPS=5000 # 5 GB (or so)
# --- Post Image creation options ---
# VERIFY_IMAGE=1
# PISHRINK_IMAGE=0
# PISHRINK_AND_GZIP_IMAGE=0
# Get hostname of system
HOSTNAME=$(hostname -s)
# Get codename of OS
VERSION_CODENAME=$(get_codename)
# Add hostname / OS codename to backup path
BACKUP_PATH="${BACKUP_ROOT}/${HOSTNAME}/${VERSION_CODENAME}"
# Save date and time to add to filename
BACKUP_DATO=$(date "+%F@%H-%M-%S")
# Detect Architecture (32 vs 64) - for filename
BITS=$(getconf LONG_BIT)
ARCHITECTURE="${BITS}bits"
# Detect OS Codename (fallback if necessary)
if [ -f /etc/os-release ]; then
# shellcheck source=/dev/null
. /etc/os-release
OS_NAME=$VERSION_CODENAME
# Fallback for older versions that don't use VERSION_CODENAME
[ -z "$OS_NAME" ] && OS_NAME=$(echo "$VERSION" | grep -oE '[a-z]+' | head -1)
else
OS_NAME="unknown"
fi
# Define Gotify message variables
GOTIFY_MESSAGE_TITLE="${HOSTNAME} Nightly Backup status"
GOTIFY_MESSAGE_PRIORITY=5
# Default behavior: Full Image
BACKUP_MODE="FULL"
COMPRESS_USER="FALSE"
# If run with sudo, get the original user; otherwise, get current user
REAL_USER=${SUDO_USER:-$(whoami)}
USER_DIR="/home/$REAL_USER"
# Check for flags - THESE TAKE PRESIDENCE OVER ANY IMAGE BACKUP
# The command line Flag Parser (added 'c')
while getopts "uci" opt; do
case $opt in
u) BACKUP_MODE="USER" ;;
c) COMPRESS_USER="TRUE" ;;
i) FORCED_INITIAL="TRUE" ;;
*) echo "Usage: $0 [-u] [-c] [-i]" && exit 1 ;;
esac
done
# --- The "Mutual Exclusion" Check ---
# If -i is TRUE, check if -u or -c were also set
if [[ "$FORCED_INITIAL" == "TRUE" ]]; then
if [[ "$BACKUP_MODE" == "USER" || "$COMPRESS_USER" == "TRUE" ]]; then
echo "Error: The -i flag cannot be used with -u or -c."
echo "Usage: $0 [-u -c] OR [-i]"
exit 1
fi
fi
# 1. First, check if the backup drive/path is even mounted
if [ ! -f "$MARKER_FILE" ]; then
echo "ERROR: Marker file $MARKER_FILE not found! The backup drive might be unmounted. Aborting to save SD card space." >&2
# Try to log it, but don't worry if it fails
echo "ERROR: The backup drive might be unmounted. Aborting..." | do_log 2>/dev/null
send_messages "❌ Backup FAILED for $HOSTNAME. BACKUP DRIVE NOT FOUND. Check Backup_pi.log"
# send_log_messages # NO LOG CREATED YET
exit 1
fi
# BACKUP_MODE selection...
if [[ ("$BACKUP_TYPE" == "user" || ("$BACKUP_MODE" == "USER" && "$COMPRESS_USER" != "TRUE")) && "$FORCED_INITIAL" != "TRUE" ]]; then
BACKUP_MODE="USER"
START_MSG="Initiating UNCOMPRESSED User Backup (-u) for $REAL_USER"
# Re-Set log filename using user directory
LOG_TO_FILE_FILENAME="user_files_${REAL_USER}_${BACKUP_DATO}.log"
elif [[ ("$BACKUP_TYPE" == "user compressed" || "$COMPRESS_USER" == "TRUE") && "$FORCED_INITIAL" != "TRUE" ]]; then
BACKUP_MODE="USER"
COMPRESS_USER="TRUE"
START_MSG="Initiating COMPRESSED User Backup (-uc) for $REAL_USER to: user_backup_${REAL_USER}_${BACKUP_DATO}.tar.gz"
# Re-Set log filename using user directory
LOG_TO_FILE_FILENAME="user_backup_${REAL_USER}_${BACKUP_DATO}.tar.gz.log"
elif [[ "$BACKUP_TYPE" == "image incremental" && "$FORCED_INITIAL" != "TRUE" ]]; then
BACKUP_MODE="IMAGE INCREMENTAL"
if ! FILENAME=$(find_incremental_file); then
# if [ $? -ne 0 ]; then
exit 1 # Now the main script actually stops
fi
START_MSG="INCREMENTAL IMAGE Backup on $HOSTNAME to: $FILENAME at $(date)"
LOG_TO_FILE_FILENAME="Backup_pi-${FILENAME}.log"
else
FILENAME="${HOSTNAME}-${OS_NAME}-${ARCHITECTURE}-${BACKUP_DATO}.img"
if [[ "$PISHRINK_AND_GZIP_IMAGE" == "1" && "$FORCED_INITIAL" != "TRUE" ]]; then # PISHRINK_AND_GZIP_IMAGE
START_MSG="FULL SYSTEM IMAGE Backup on $HOSTNAME to: $FILENAME.gz at $(date)"
LOG_TO_FILE_FILENAME="Backup_pi-${FILENAME}.gz.log"
else
START_MSG="FULL SYSTEM IMAGE Backup on $HOSTNAME to: $FILENAME at $(date)"
LOG_TO_FILE_FILENAME="Backup_pi-${FILENAME}.log"
fi
BACKUP_MODE="IMAGE"
fi
# SET full backup path
FULL_PATH="${BACKUP_PATH}/${FILENAME}"
# IF logging is selected then set full log path
if [[ "$LOG_TO_FILE" == "1" ]]; then
# Combine the directory and filename into one quoted string for safety
FULL_LOG_PATH="$LOG_TO_FILE_DIRECTORY/$LOG_TO_FILE_FILENAME"
fi
# Check for necessary commands and when found read full path of command into a variable like $RSYNC_BIN (? in front of optional commands)
check_commands rsync fstrim image-backup image-info "?pishrink.sh" "?telegram-send" "?telegram-send-group-topic.sh" "?telegram-send-group-topic-file.sh" "?gotify-send.sh" "?ntfy-send.sh" "?ntfy-send-file.sh"
# NOT STRICTLY NECESSARY IF NOT USED - pishrink.sh telegram-send-group-topic.sh telegram-send-group-topic-file.sh gotify-send.sh ntfy-send.sh ntfy-send-file.sh
# echo "$RSYNC_BIN"
# echo "$FSTRIM_BIN"
# echo "$IMAGE_BACKUP_BIN"
# echo "$IMAGE_INFO_BIN"
# echo "$PISHRINK_BIN"
# echo "$TELEGRAM_SEND_BIN"
# echo "$TELEGRAM_SEND_GROUP_TOPIC_BIN"
# echo "$TELEGRAM_SEND_GROUP_TOPIC_FILE_BIN"
# echo "$GOTIFY_SEND_BIN"
# echo "$NTFY_SEND_BIN"
# echo "$NTFY_SEND_FILE_BIN"
# exit 0
# Define the source device (SD card or USB)
if [ -b "/dev/mmcblk0" ]; then
SOURCE_DEV="/dev/mmcblk0"
else
SOURCE_DEV="/dev/sda"
fi
# Print a separator and timestamp to the terminal, then log
echo "---------------------------------------------------"
echo "Backup started at: $(date)"
echo "System Detected: $OS_NAME ($ARCHITECTURE)"
echo "Device to back up: $SOURCE_DEV"
echo "Type: $START_MSG"
if [[ "$LOG_TO_FILE" == "1" ]]; then
echo "Log file: $FULL_LOG_PATH"
fi
echo ""
if [[ "$LOG_TO_FILE" == "1" ]]; then
log_directory_check
if [[ "$BACKUP_MODE" == "IMAGE INCREMENTAL" ]]; then
{
echo "---------------------------------------------------"
echo "----------------INCREMENTAL UPDATE-----------------"
echo "---------------------------------------------------"
} >>"$FULL_LOG_PATH"
else
echo "---------------------------------------------------" >"$FULL_LOG_PATH"
fi
{
echo "Backup started at: $(date)"
echo "System Detected: $OS_NAME ($ARCHITECTURE)"
echo "Device to back up: $SOURCE_DEV"
echo "Type: $START_MSG"
echo "Log file: ""$LOG_TO_FILE_DIRECTORY"/"$LOG_TO_FILE_FILENAME"""
echo ""
} >>"$FULL_LOG_PATH"
fi
# Send start message if set to send messages and not restricted to some messages only
if [[ "$SEND_MESSAGES_ONLY_ON_ERROR" != "1" && "$SEND_CONFIRMATON_MESSAGE_ONLY" != "1" ]]; then
send_messages "🚀 BEGINNING: $START_MSG"
fi
echo "" | do_log
# Check if not user backup - if so set up file for image expanding & trim partitions
if [[ "$BACKUP_MODE" != "USER" ]]; then
# Ensure /etc/rc.local exists for PiShrink
if [[ ! -f /etc/rc.local ]]; then
echo "NOTICE: /etc/rc.local missing. Creating for PiShrink and image-backup auto-expand..." | do_log
# Create the basic script structure
# Using 'printf' to avoid escape character issues
printf '%s\n' '#!/bin/bash' '' 'exit 0' | sudo tee /etc/rc.local >/dev/null
# Make it executable (This is the "trigger" for Systemd)
sudo chmod +x /etc/rc.local
# Reload systemd so it notices the new file immediately
sudo systemctl daemon-reload >/dev/null 2>&1
echo "SUCCESS: /etc/rc.local created. Expansion code available for injection." | do_log
fi
if [[ "$SOURCE_DEV" == "/dev/mmcblk0" ]]; then
# Clean up unused blocks to make the final image compress better
echo "Reducing filesize by using fstrim..." | do_log
echo "" | do_log
# Identify the VFAT boot partition dynamically
BOOT_PART=$(lsblk -lno NAME,FSTYPE | grep vfat | awk '{print "/dev/"$1}' | head -n 1)
TEMP_MOUNT="/mnt/boot_temp"
# Check if it's already mounted somewhere
CURRENT_MOUNT=$(findmnt -nvo TARGET "$BOOT_PART")
if [[ -n "$CURRENT_MOUNT" ]]; then
# Partition is already mounted (e.g., to /boot/firmware)
stdbuf -oL "$FSTRIM_BIN" -v "$CURRENT_MOUNT" 2>&1 | do_log
stdbuf -oL "$FSTRIM_BIN" -v / 2>&1 | do_log
elif [[ -b "$BOOT_PART" ]]; then
# Partition needs temporary mounting
mkdir -p "$TEMP_MOUNT"
echo "Boot partition not mounted. Mounting temporarily..." | do_log
echo "" | do_log
if mount "$BOOT_PART" "$TEMP_MOUNT"; then
stdbuf -oL "$FSTRIM_BIN" -v "$TEMP_MOUNT" 2>&1 | do_log
sleep 1
umount "$TEMP_MOUNT"
fi
# Always trim root last
stdbuf -oL "$FSTRIM_BIN" -v / 2>&1 | do_log
else
echo "Warning: Could not identify a VFAT boot partition. Trimming root only." | do_log
stdbuf -oL "$FSTRIM_BIN" -v / 2>&1 | do_log
fi
echo "" | do_log
fi
fi
# Verify the backup drive is actually mounted
# This looks for a "Marker file" in the root of the backup path (as defined in .conf)
echo "Checking for backup destination..." | do_log
echo "" | do_log
# Look for marker file existence - means backup destination is available
if [ ! -f "$MARKER_FILE" ]; then
echo "ERROR: Marker file $MARKER_FILE not found! The backup drive might be unmounted. Aborting to save SD card space." | do_log
echo "" | do_log
# # send error notifications
send_messages "❌ Backup FAILED for $HOSTNAME. BACKUP DRIVE NOT FOUND. Check Backup_pi.log"
send_log_messages
exit 1
fi
# Must have found marker file - proceed with backup
echo "USB Marker found. Proceeding with backup..." | do_log
echo "" | do_log
directory_check # Make sure backup directory exists on backup drive
# # NOT USED - This checks if the backup path lives on the same drive as the OS (/)
# # If they are the same, it means the USB isn't mounted.
# if [ "$(stat -c%d /)" = "$(stat -c%d "$BACKUP_PATH")" ]; then
# echo "ERROR: $BACKUP_PATH appears to be on the SD card, not the USB drive! Aborting."
# exit 1
# fi
# if ! mountpoint -q "$BACKUP_PATH"; then
# echo "ERROR: Backup destination $BACKUP_PATH is NOT a mountpoint. Aborting to save SD card space."
# exit 1
# fi
# Resource Check: USB Capacity (90% Threshold)
# Extracts the capacity percentage of the backup mount point
USB_USAGE=$(df "$BACKUP_PATH" | awk 'NR==2 {print $5}' | sed 's/%//')
if [ "$USB_USAGE" -gt 90 ]; then
WARN_MSG="WARNING: USB Storage at ${USB_USAGE}% capacity! Resources critical."
echo "$WARN_MSG" | do_log
echo "" | do_log
if [[ "$SEND_MESSAGES_ONLY_ON_ERROR" != "1" && "$SEND_CONFIRMATON_MESSAGE_ONLY" != "1" ]]; then
send_messages "⚠️ $WARN_MSG"
echo "" | do_log
fi
# Optional: exit 1 <-- Add this if you want to abort the backup when full
fi
if [[ "$UNMOUNT_CUSTOM_MOUNTS_PRIOR_TO_BACKUP" == "1" ]]; then
echo "Checking for custom mounts to unmount prior to starting the backup..." | do_log
echo "" | do_log
find_custom_mounts
if [ ${#FSTAB_MOUNTS[@]} -gt 0 ] || [ ${#MANUAL_MOUNTS[@]} -gt 0 ]; then
echo "Unmounting the custom mounts found..." | do_log
unmount_custom_mounts
echo "" | do_log
fi
fi
# START BACKUP PROCESSING - USER BACKUP MODES FIRST
if [[ "$BACKUP_MODE" == "USER" ]]; then
# 1. Check if the home directory exists before proceeding
if [[ -d "$USER_DIR" ]]; then
if [[ "$COMPRESS_USER" == "TRUE" ]]; then
BACKUP_FILE="${BACKUP_PATH}/user_backup_${REAL_USER}_${BACKUP_DATO}.tar.gz"
echo "Detected user: $REAL_USER. Backing up to $BACKUP_FILE..." | do_log
# 1. Create compressed archive (removed -W)
# Add --ignore-failed-read to bypass permission blocks
# Run the tar command
tar -czpf "$BACKUP_FILE" --ignore-failed-read --warning=no-file-changed --one-file-system --exclude="$USER_DIR/.cache" --exclude="$USER_DIR/.local/share/Trash" "$USER_DIR" 2> >(grep -v "Removing leading" >&2) | do_log
# Capture the exit code of tar (first in the pipe)
TAR_EXIT=${PIPESTATUS[0]}
# Now check if it was 0 OR 1
if [[ $TAR_EXIT -eq 0 || $TAR_EXIT -eq 1 ]]; then
echo "" | do_log
# 2. Verify the compressed file integrity
echo "Verifying archive integrity..." | do_log
if gunzip -t "$BACKUP_FILE" 2>&1 | do_log; then
echo "SUCCESS: Archive is valid and healthy." | do_log
# Calculate and log the final size
FINAL_SIZE=$(du -sh "$BACKUP_FILE" | awk '{print $1}')
echo "COMPLETED: Backup saved to $BACKUP_FILE (Size: $FINAL_SIZE)" | do_log
echo "" | do_log
MESSAGE="✅ Backup Successful for $HOSTNAME to: $BACKUP_FILE (Size: $FINAL_SIZE)"
send_messages "$MESSAGE"
echo "" | do_log
FINAL_REPORT="🏁 *Backup Mission Debrief* 🏁
---------------------------------
👤 User: $REAL_USER
📦 Mode: $BACKUP_MODE COMPRESSED
📋 File: user_backup_${REAL_USER}_${BACKUP_DATO}.tar.gz
📊 Size: $FINAL_SIZE
🛡️ Integrity: VERIFIED
---------------------------------"
# ⏱️ Time: $DURATION
# ♻️ Purge Status: $PURGE_RESULT"
else
echo "CRITICAL ERROR: Archive verification failed!" | do_log
exit 1
fi
else
echo "ERROR: Tar command failed during creation." | do_log
exit 1
fi
# Set pattern to search for when purging backups
BACKUP_PATTERN="user_backup_${REAL_USER}_"
pushd "${BACKUP_PATH}" >/dev/null || echo "Warning: Could not save current directory" | do_log
if ((USER_BACKUP_ANTAL > 0)); then
# # # 1. Identify files to delete (filtering out full system images)
# For Compressed Files
rotate_backups_and_logs "$BACKUP_PATTERN" "$USER_BACKUP_ANTAL" "Compressed Backups"
else
echo "Warning: USER_BACKUP_ANTAL is 0. Skipping purge to prevent total data loss." | do_log
fi
# Set pattern to search for when purging log files
LOG_PATTERN="user_backup_${REAL_USER}_"
else
# --- OPTION B: Straight Copy (Structure Only) ---
# We use rsync to keep permissions, links, and times intact
DEST_DIR="${BACKUP_PATH}/user_files_${REAL_USER}_${BACKUP_DATO}"
echo "Mode: Uncompressed Structure. Target: $DEST_DIR" | do_log
mkdir -p "$DEST_DIR"
# -a: archive mode (preserves everything)
# -v: verbose (so do_log catches the file list)
"$RSYNC_BIN" -av "$USER_DIR/" "$DEST_DIR/" 2>&1 | do_log
FINAL_SIZE=$(du -sh "$DEST_DIR" | awk '{print $1}')
echo "" | do_log
echo "Backup Successful for $HOSTNAME from: $USER_DIR/ to: $DEST_DIR (Size: $FINAL_SIZE)" | do_log
echo "" | do_log