-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbackup_plex.sh
More file actions
executable file
Β·874 lines (791 loc) Β· 32.8 KB
/
backup_plex.sh
File metadata and controls
executable file
Β·874 lines (791 loc) Β· 32.8 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
#!/usr/bin/env bash
# _____ _ ____ _ _____ _ _
# | __ \ | | _ \ | | / ____| (_) | |
# | |__) | | _____ __| |_) | __ _ ___| | ___ _ _ __ | (___ ___ _ __ _ _ __ | |_
# | ___/| |/ _ \ \/ /| _ < / _` |/ __| |/ / | | | '_ \ \___ \ / __| '__| | '_ \| __|
# | | | | __/> < | |_) | (_| | (__| <| |_| | |_) | ____) | (__| | | | |_) | |_
# |_| |_|\___/_/\_\|____/ \__,_|\___|_|\_\\__,_| .__/ |_____/ \___|_| |_| .__/ \__|
# | | | |
# |_| |_|
# ==========================================================
# π¬ backup-plex - A script to backup your Plex database
# π§ Author: Drazzilb | π» Version: 6.0.0 | π License: MIT
# ==========================================================
# This script performs scheduled backups of a Plex Media Server instance.
# Supports full or essential backups, compression, verification, restore, and webhook notifications.
script_version="6.0.0"
## Display help message and usage instructions
display_help() {
cat <<EOF
π¦ Plex Backup Script - Version $script_version
Usage:
\$0 [options]
Options:
-s, --source <dir> Source Plex data directory
-d, --destination <dir> Destination for backups
-k, --keep-essential <num> Number of Essential backups to retain
-K, --keep-full <num> Number of Full backups to retain
-F, --force-full <days> Run full backup every X days
-f, --full-backup Enable full backup mode
-c, --compress Compress backups using 7z
-r, --dry-run Simulate run without changes
-S, --shutdown Shut down Plex during backup
-q, --quiet Suppress output
-u, --unraid-notify Use Unraid's notify system
-w, --webhook <url> Discord or Notifiarr webhook
-C, --channel <id> Notifiarr channel ID
-b, --bar-color <hex> Hex color for notifications
-n, --bot-name <name> Bot name (for Discord)
-D, --debug Enable debug logging
-x, --use-config <true|false> Use config file or not
--restore Restore the most recent backup
--test-restore Simulate restore to a temporary test directory
-h, --help Show this help message
Example:
bash \$0 -s /mnt/appdata/plex -d /mnt/backups/plex -f -c -w https://discord.com/api/webhooks/...
EOF
}
IS_TTY=false
if [[ -t 1 ]]; then
IS_TTY=true
fi
log() {
local msg="$1"
# Strip color codes for log file (ANSI escape sequences)
local plain_msg
plain_msg="$(echo -e "$msg" | sed -r 's/\x1b\[[0-9;]*m//g')"
if [[ -n "$LOG_FILE" ]]; then
echo -e "$plain_msg" >> "$LOG_FILE"
fi
# Only print to terminal if not quiet and output is a TTY
if $IS_TTY && [[ "${quiet,,}" != "true" ]]; then
echo -e "$msg"
fi
}
## Handle CLI arguments and map to script variables
handle_options() {
bar_color='e5a00d'
use_config_file="true"
shutdown_plex="false"
dry_run="false"
TEMP=$(getopt -o s:d:k:c:w:C:K:F:f:r:S:D:x:q:u:b:n:h --long help,restore,test-restore -- "$@")
eval set -- "$TEMP"
while true; do
case "$1" in
-s) source_dir="$2"; shift 2 ;;
-d) destination_dir="$2"; shift 2 ;;
-k) keep_essential="$2"; shift 2 ;;
-c) compress="$2"; shift 2 ;;
-w) webhook="$2"; shift 2 ;;
-C) channel="$2"; shift 2 ;;
-K) keep_full="$2"; shift 2 ;;
-F) force_full_backup="$2"; shift 2 ;;
-f) full_backup="$2"; shift 2 ;;
-r) dry_run="$2"; shift 2 ;;
-S) shutdown_plex="$2"; shift 2 ;;
-D) debug="$2"; shift 2 ;;
-x) use_config_file="$2"; shift 2 ;;
-q) quiet="$2"; shift 2 ;;
-u) unraid_notify="$2"; shift 2 ;;
-b) bar_color="$2"; shift 2 ;;
-n) bot_name="$2"; shift 2 ;;
--restore) restore_flag="true"; shift ;;
--test-restore) test_restore_flag="true"; shift ;;
-h|--help) display_help; shift ;;
--) shift; break ;;
*) break ;;
esac
done
}
## Set up configuration file paths and script directory
config_dir_setup() {
config_dir=$(dirname "$(readlink -f "$0")")
script_path=$(dirname "$0")
config_file="$script_path/backup_plex.conf"
}
## Load configuration from file if it exists
load_config_file() {
if [ -f "$config_file" ]; then
source "$config_file"
# If debug is set print this statement
if [[ "${debug,,}" == "true" ]]; then
echo "βοΈ Config file exists and is accessible."
fi
fi
}
## Validate directory paths and webhook if defined
check_config() {
if [ ! -d "$source_dir" ]; then
echo "β ERROR: Your source directory ($source_dir) does not exist"
exit 0
fi
if [ -z "$source_dir" ]; then
echo "β ERROR: Your source directory is not set"
exit 0
fi
if [ ! -d "$destination_dir" ]; then
echo "β ERROR: Your destination directory ($destination_dir) does not exist"
exit 0
fi
if [ -z "$destination_dir" ]; then
echo "β ERROR: Your destination directory is not set"
exit 0
fi
if [[ "${compress,,}" == "true" ]]; then
if ! command -v zstd >/dev/null && ! command -v zstdcat >/dev/null; then
echo "β Compression enabled but neither zstd nor 7z is installed."
exit 1
fi
fi
if [ -n "$webhook" ]; then
if [[ ! $webhook =~ ^https://discord\.com/api/webhooks/ ]] && [[ ! $webhook =~ ^https://notifiarr\.com/api/v1/notification/passthrough ]]; then
echo "β ERROR: Invalid webhook format"
exit 0
fi
if [[ $webhook =~ notifiarr ]] && [ -z "$channel" ]; then
echo "β ERROR: Notifiarr webhook requires a channel ID (-C)"
exit 0
fi
if [[ $webhook =~ notifiarr ]]; then
apikey="${webhook##*/}"
[ "${debug,,}" == "true" ] && echo "π‘ Validating Notifiarr webhook: $webhook"
response_code=$(curl --write-out "%{response_code}" --silent --output /dev/null \
-H "x-api-key: $apikey" "https://notifiarr.com/api/v1/user/validate")
else
[ "${debug,,}" == "true" ] && echo "π‘ Validating Discord webhook: $webhook"
response_code=$(curl --write-out "%{response_code}" --silent --output /dev/null "$webhook")
fi
[ "${debug,,}" == "true" ] && echo "π Response: $response_code"
if [ "$response_code" -eq 200 ]; then
if [[ "${debug,,}" == "true" ]]; then
echo "β
Webhook is valid"
fi
else
echo "β οΈ Webhook is not valid. Continuing without notifications."
fi
fi
}
## Convert a hex color code to decimal for Discord/Notifiarr embeds
hex_to_decimal() {
if [[ $bar_color =~ ^\#[0-9A-Fa-f]{6}$ ]]; then
hex_bar_color=${bar_color:1}
decimal_bar_color=$((0x${bar_color:1}))
elif [[ $bar_color =~ ^[0-9A-Fa-f]{6}$ ]]; then
hex_bar_color=$bar_color
decimal_bar_color=$((0x$bar_color))
else
echo "Bar color: $bar_color"
echo -e "β Invalid color format. Use 6-digit hex (e.g. ff0000)"
exit 0
fi
}
## Clean up old backups beyond the retention limit
cleanup_function() {
log "π£ Cleaning up old backups..."
destination_dir=$(realpath -s "$destination_dir")
if [ -d "$destination_dir/Essential" ]; then
log "π§Ή Looking for old Essential backups (keeping last $keep_essential)..."
find "$destination_dir/Essential" -mindepth 1 -maxdepth 1 -type d | sort -r | tail -n +$(( keep_essential + 1 )) | while read -r dir; do
log "π Removing: $dir"
rm -rf "$dir"
done
fi
if [ -d "$destination_dir"/Full ]; then
log "π§Ή Looking for old Full backups (keeping last $keep_full)..."
find "$destination_dir/Full" -mindepth 1 -maxdepth 1 -type d | sort -r | tail -n +$(( keep_full + 1 )) | while read -r dir; do
log "π Removing: $dir"
rm -rf "$dir"
done
log "β
Done\n"
fi
}
## Calculate total runtime of the backup process
calculate_runtime() {
total_time=$((end - start))
seconds=$((total_time % 60))
minutes=$((total_time % 3600 / 60))
hours=$((total_time / 3600))
if ((minutes == 0 && hours == 0)); then
run_output="β±οΈ Backup completed in $seconds seconds"
elif ((hours == 0)); then
run_output="β±οΈ Backup completed in $minutes minutes and $seconds seconds"
else
run_output="β±οΈ Backup completed in $hours hours $minutes minutes and $seconds seconds"
fi
}
## Send a system notification to Unraid (if enabled)
unraid_notification() {
case "$backup_type" in
essential) /usr/local/emhttp/webGui/scripts/notify -e "Unraid Server Notice" -s "Plex Backup" -d "Essential Plex data has been backed up" -i "normal" ;;
full) /usr/local/emhttp/webGui/scripts/notify -e "Unraid Server Notice" -s "Plex Backup" -d "Full Plex data has been backed up" -i "normal" ;;
both) /usr/local/emhttp/webGui/scripts/notify -e "Unraid Server Notice" -s "Plex Backup" -d "Essential & Full Plex data has been backed up" -i "normal" ;;
esac
}
## Send a webhook notification to Discord or Notifiarr
send_notification() {
if [[ -n "$webhook" ]]; then
[ "${full_backup,,}" == "true" ] && echo -e "\ncurl -X POST -d '$payload' $webhook"
curl -s -H "Content-Type: application/json" -X POST -d "$payload" "$webhook" --output /dev/null
fi
}
## Format field entries for the webhook JSON payload
field_builder() {
local title_text="$1"
local text_value="$2"
local reset="$3"
if [ "$reset" == "true" ]; then
fields=""
fi
local block='{
"'"$title"'": "'"$title_text"'",
"'"$text"'": "'"$text_value"'",
"inline": false
}'
[ -n "$fields" ] && block=",$block"
fields="${fields}${block}"
}
## Assemble the webhook JSON payload
build_payload() {
get_ts=$(date -u -Iseconds)
joke=$(curl -s https://raw.githubusercontent.com/Drazzilb08/daps/master/jokes.txt | shuf -n 1 | sed 's/"/\\"/g')
if [[ $webhook =~ discord ]]; then
bot_name="Notification Bot"
title="name"
text="value"
common_fields='{
"username": "'"$bot_name"'",
"embeds": [{
"title": "Plex Backup",'
common_fields2='"footer": { "text": "Powered by: Drazzilb | '"$joke"'" },
"color": '"$decimal_bar_color"',
"timestamp": "'"$get_ts"'"
}]
}'
elif [[ $webhook =~ notifiarr ]]; then
title="title"
text="text"
common_fields='{
"notification": {
"update": false,
"name": "Plex Backup",
"event": ""
},
"discord": {
"color": "'"$hex_bar_color"'",
"text": {
"title": "Plex Backup",'
common_fields2='
"footer": "Powered by: Drazzilb | '"$joke"'"
},
"ids": {
"channel": "'"$channel"'"
}
}
}'
fi
}
## Wrap final payload into complete notification structure
payload() {
local description="$1"
payload="${common_fields}
\"description\": \"$description\",
\"fields\": [
$fields
],
$common_fields2"
}
## Perform a Zstandard compressed backup
zst_backup() {
extension="zst"
if [ "$dry_run" == "true" ]; then
extension+=".dry_run"
log "π§ͺ Dry run: Creating dummy file at: $backup_path/$folder_type-plex_backup.$extension"
touch "$backup_path/$folder_type-plex_backup.$extension"
return
fi
log "π¦ Creating Zstandard archive..."
dir_size=$(cd "$source_dir" && du -sb --exclude="${exclude[*]#--exclude=}" "${backup_source[@]}" 2>/dev/null | awk '{sum+=$1} END{print sum}')
if [[ -z "$dir_size" || "$dir_size" -eq 0 ]]; then
log "β ERROR: Nothing to archive. The source may be empty or incorrectly specified."
backup_failed=true
return
fi
if $IS_TTY; then
( cd "$source_dir" &&
tar --ignore-failed-read -cf - --transform "s|^|$base_dir_name/|" "${exclude[@]}" "${backup_source[@]}"
) | \
pv --size "$dir_size" --progress --timer --rate --eta --bytes --name BACKUP --force --width "$(($(tput cols)-10))" | \
zstd -q --threads=0 -19 -o "$backup_path/$folder_type-plex_backup.zst"
else
( cd "$source_dir" &&
tar --ignore-failed-read -cf - --transform "s|^|$base_dir_name/|" "${exclude[@]}" "${backup_source[@]}"
) | \
zstd -q --threads=0 -19 -o "$backup_path/$folder_type-plex_backup.zst"
fi
}
## Perform a 7z compressed backup
7z_backup() {
extension="7z"
if [ "$dry_run" == "true" ]; then
extension+=".dry_run"
log "π§ͺ Dry run: Creating dummy file at: $backup_path/$folder_type-plex_backup.$extension"
touch "$backup_path/$folder_type-plex_backup.$extension"
return
fi
log "π¦ Creating 7z archive..."
dir_size=$(cd "$source_dir" && du -sb --exclude="${exclude[*]#--exclude=}" "${backup_source[@]}" | awk '{sum+=$1} END{print sum}')
if $IS_TTY; then
( cd "$source_dir" &&
tar --ignore-failed-read -cf - --transform "s|^|$base_dir_name/|" "${exclude[@]}" "${backup_source[@]}"
) | \
pv --size "$dir_size" --progress --timer --rate --eta --bytes --name BACKUP --force --width "$(($(tput cols)-10))" | \
7z a -si -t7z -m0=lzma2 -mx=3 -md=16m -mfb=32 -mmt=on -ms=off "$backup_path/$folder_type-plex_backup.7z" >/dev/null
else
( cd "$source_dir" &&
tar --ignore-failed-read -cf - --transform "s|^|$base_dir_name/|" "${exclude[@]}" "${backup_source[@]}"
) | \
7z a -si -t7z -m0=lzma2 -mx=3 -md=16m -mfb=32 -mmt=on -ms=off "$backup_path/$folder_type-plex_backup.7z" >/dev/null
fi
}
## Perform a tar archive backup with optional progress
tar_backup() {
extension="tar"
if [ "$dry_run" == "true" ]; then
extension+=".dry_run"
log "π§ͺ Dry run: Creating dummy file at: $backup_path/$folder_type-plex_backup.$extension"
touch "$backup_path/$folder_type-plex_backup.$extension"
else
if $IS_TTY && command -v pv >/dev/null; then
log "π¦ Creating archive..."
dir_size=$(cd "$source_dir" && du -sb --exclude="${exclude[*]#--exclude=}" "${backup_source[@]}" | awk '{sum+=$1} END{print sum}')
( cd "$source_dir" &&
tar --ignore-failed-read \
--blocking-factor=128 \
--no-check-device \
-cf - \
--transform "s|^|$base_dir_name/|" \
"${exclude[@]}" "${backup_source[@]}"
) | \
pv --size "$dir_size" --progress --timer --rate --eta --bytes --name BACKUP --force --width "$(($(tput cols) - 10))" > "$backup_path/$folder_type-plex_backup.$extension"
else
log "π¦ Creating archive..."
( cd "$source_dir" &&
tar --ignore-failed-read -cf - --transform "s|^|$base_dir_name/|" "${exclude[@]}" "${backup_source[@]}"
) > "$backup_path/$folder_type-plex_backup.$extension"
fi
if tar -tf "$backup_path/$folder_type-plex_backup.$extension" >/dev/null; then
log "\nβ
Verified: tar archive is readable"
else
log "\nβ ERROR: tar archive verification failed!"
backup_failed=true
fi
fi
}
## Primary function to create a backup (Essential or Full)
create_backup() {
local folder_type=$1
log "\n=============================== π¦ $folder_type Backup ==============================="
[ "$dry_run" == "true" ] && log "π§ͺ Dry run mode enabled β no files will be created or modified."
source_dir=${source_dir%/}
base_dir_name=$(basename "$source_dir")
start=$(date +%s)
backup_failed=false
dest=$(realpath -s "$destination_dir")
now="$(date +"%H.%M")"
backup_path="$dest/$folder_type/$(date +%F)@$now"
mkdir -p "$backup_path"
if [ "$folder_type" == "Essential" ]; then
backup_source=(
"Plug-in Support/Databases"
"Plug-in Support/Preferences"
"Preferences.xml"
)
exclude=(
"--exclude=Plug-in Support/Databases/dbtmp"
)
else
backup_source=(".")
exclude=(
"--exclude=Cache"
"--exclude=Codecs"
"--exclude=Crash Reports"
"--exclude=Diagnostics"
"--exclude=Drivers"
"--exclude=Logs"
)
fi
if [ "$compress" == "true" ]; then
if command -v zstd >/dev/null; then
zst_backup
else
7z_backup
fi
else
tar_backup
fi
if [ "$folder_type" == "Essential" ]; then
essential_backup_size=$(du -sh "$backup_path/$folder_type-plex_backup.$extension" | awk '{print $1}')
else
full_backup_size=$(du -sh "$backup_path/$folder_type-plex_backup.$extension" | awk '{print $1}')
fi
full_backup_total_size=$( [ -d "$dest/Full/" ] && du -sh "$dest/Full/" | awk '{print $1}' || echo "0B" )
essential_backup_total_size=$( [ -d "$dest/Essential/" ] && du -sh "$dest/Essential/" | awk '{print $1}' || echo "0B" )
end=$(date +%s)
if [ "$backup_failed" == "true" ]; then
build_payload
field_builder "Backup Status" "β Archive verification failed" "true"
payload "Backup Failure"
send_notification
log "β Backup verification failed. Notification sent."
return
fi
log "\nβ
Backup complete."
calculate_runtime
if [ "$dry_run" == "true" ]; then
essential_backup_size="1.0G"
full_backup_size="1.0G"
full_backup_total_size="2.0G"
essential_backup_total_size="2.0G"
run_output="π§ͺ Dry Run: Simulated runtime"
fi
}
## Detect whether Plex is running as Docker or systemd
get_plex_type() {
if docker ps --format '{{.Names}}' 2>/dev/null | grep -qw plex; then
plex_type="docker"
elif [[ $(systemctl is-active plexmediaserver 2>/dev/null) == "active" ]]; then
plex_type="systemctl"
else
echo "β ERROR: Plex is not running in Docker or systemctl"
exit 1
fi
}
## Stop Plex before backup if enabled
stop_plex() {
if [ "$shutdown_plex" == "true" ] && [ "$dry_run" != "true" ]; then
case "$backup_type" in
essential|essential_no_full) backup_notification="Essential Backup" ;;
full) backup_notification="Full Backup" ;;
both) backup_notification="Essential & Full Backup" ;;
esac
get_plex_tyupe
[[ "${full_backup,,}" == "true" ]] && log "π» Plex detected as: $plex_type"
if [ "$plex_type" == "docker" ]; then
log "π Stopping Docker Plex..."
docker stop plex
elif [ "$plex_type" == "systemctl" ]; then
log "π Stopping systemd Plex..."
systemctl stop plexmediaserver.service
fi
build_payload
field_builder "Plex is being shut down for a backup" "true"
payload "Plex Status"
send_notification
fi
}
## Restart Plex after backup if enabled
start_plex() {
if [ "$shutdown_plex" == "true" ]; then
case "$backup_type" in
essential|essential_no_full) backup_notification="Essential Backup" ;;
full) backup_notification="Full Backup" ;;
both) backup_notification="Essential & Full Backup" ;;
esac
[[ "${full_backup,,}" == "true" ]] && log "πΌ Starting Plex ($plex_type)..."
if [ "$plex_type" == "docker" ]; then
log "π Starting Docker Plex..."
docker start plex
elif [ "$plex_type" == "systemctl" ]; then
log "π Starting systemd Plex..."
systemctl start plexmediaserver.service
else
log "β ERROR: Plex type unknown. Cannot start."
exit 1
fi
build_payload
field_builder "Plex is being started after" "$backup_notification" "true"
payload "Plex Status"
send_notification
fi
}
## Display debug output of current variables and runtime state
debug_output_function() {
log "\n===================== DEBUG INFO ====================="
log "$(printf "%-25s %s" "Debug:" "$debug")"
log "$(printf "%-25s %s" "Source:" "$source_dir")"
log "$(printf "%-25s %s" "Destination:" "$destination_dir")"
log "$(printf "%-25s %s" "Keep essential:" "$keep_essential")"
log "$(printf "%-25s %s" "Keep full:" "$keep_full")"
log "$(printf "%-25s %s" "Full backup:" "$full_backup")"
log "$(printf "%-25s %s" "Force full backup:" "$force_full_backup")"
log "$(printf "%-25s %s" "Unraid notify:" "$unraid_notify")"
log "$(printf "%-25s %s" "Compress:" "$compress")"
log "$(printf "%-25s %s" "Dry run:" "$dry_run")"
log "$(printf "%-25s %s" "Quiet:" "$quiet")"
log "$(printf "%-25s %s" "Webhook:" "$webhook")"
log "$(printf "%-25s %s" "Bot name:" "$bot_name")"
log "$(printf "%-25s %s" "Channel:" "$channel")"
log "$(printf "%-25s %s" "Essential size:" "$essential_backup_size")"
log "$(printf "%-25s %s" "Essential total size:" "$essential_backup_total_size")"
log "$(printf "%-25s %s" "Full size:" "$full_backup_size")"
log "$(printf "%-25s %s" "Full total size:" "$full_backup_total_size")"
log "$(printf "%-25s %s" "Days since last full:" "$days")"
log "$(printf "%-25s %s" "Bar color (hex):" "$hex_bar_color")"
log "$(printf "%-25s %s" "Bar color (decimal):" "$decimal_bar_color")"
log "$(printf "%-25s %s" "Timestamp:" "$get_ts")"
log "$(printf "%-25s %s" "Last backup recorded:" "$lastbackup")"
log "$(printf "%-25s %s" "Backup type:" "$backup_type")"
log "$(printf "%-25s %s" "Shutdown Plex:" "$shutdown_plex")"
log "$(printf "%-25s %s" "Runtime:" "$run_output")"
log "$(printf "%-25s %s" "Config directory:" "$config_dir")"
log "$(printf "%-25s %s" "Plex Type:" "$plex_type")"
log "======================================================"
}
## Restore backup from archive(s), optionally to a test location
run_restore() {
get_plex_type
echo -e "\nπ οΈ Restore Mode Activated"
echo "Which type of backup would you like to restore?"
select restore_type in "Essential" "Full" "Both" "Cancel"; do
case $restore_type in
Essential|Full|Both) break ;;
Cancel) echo "β Restore cancelled."; exit 0 ;;
*) echo "Please choose a valid option." ;;
esac
done
declare -A selected_backups
if [ "$restore_type" == "Both" ]; then
restore_types=("Full" "Essential")
else
restore_types=("$restore_type")
fi
for sub_type in "${restore_types[@]}"; do
search_dir="$destination_dir/$sub_type"
if [ ! -d "$search_dir" ]; then
echo "β No backups found in $search_dir"
exit 1
fi
echo -e "\nπ¦ Available $sub_type backups:"
mapfile -t backup_paths < <(find "$search_dir" -mindepth 1 -maxdepth 1 -type d | sort -r)
backups_list=()
for path in "${backup_paths[@]}"; do
label=$(basename "$path" | sed 's/@/ @ /')
backups_list+=("$label")
done
if [ ${#backups_list[@]} -eq 0 ]; then
echo "β No $sub_type backup directories found."
exit 1
fi
select selected_label in "${backups_list[@]}" "Cancel"; do
if [[ "$selected_label" == "Cancel" ]]; then
echo "β Restore cancelled."
exit 0
fi
for i in "${!backups_list[@]}"; do
if [[ "${backups_list[$i]}" == "$selected_label" ]]; then
selected_backups["$sub_type"]="${backup_paths[$i]}"
break 2
fi
done
echo "Please choose a valid option."
done
done
restore_target="$source_dir"
[ "$test_restore_flag" == "true" ] && restore_target="$(dirname "$0")/tmp_restore"
echo -e "\nπ Restoring from:"
for type in "${!selected_backups[@]}"; do
echo " - $type: ${selected_backups[$type]}"
done
echo "π Target location: $restore_target"
mkdir -p "$restore_target"
if [ -d "$restore_target" ] && [ "$(ls "$restore_target")" ]; then
echo "β οΈ WARNING: $restore_target is not empty and may be overwritten."
read -rp "Are you sure you want to continue? (yes/no): " confirm
[[ ! "$confirm" =~ ^[Yy](es)?$ ]] && echo "β Restore cancelled." && exit 1
fi
# Detect and shut down Plex if it's running - commented out for now for testing
if [ "$test_restore_flag" != "true" ]; then
if docker ps --format '{{.Names}}' | grep -qw plex; then
plex_type="docker"
echo "π Stopping Plex (Docker)..."
docker stop plex
elif systemctl is-active --quiet plexmediaserver; then
plex_type="systemctl"
echo "π Stopping Plex (systemd)..."
systemctl stop plexmediaserver
else
plex_type=""
echo "βΉοΈ Plex does not appear to be running."
fi
else
echo "π§ͺ Test restore: skipping Plex shutdown"
fi
for type in "${restore_types[@]}"; do
archive_dir="${selected_backups[$type]}"
archive=$(find "$archive_dir" -type f -name '*plex_backup.*' | head -n 1)
if [ ! -f "$archive" ]; then
echo "β No $type backup archive found in $archive_dir"
exit 1
fi
echo "π¦ Restoring $type backup from: $archive"
if [[ "$archive" == *.7z ]]; then
echo "π¦ Extracting .7z archive..."
if command -v pv >/dev/null; then
7z x -so "$archive" | pv | tar --strip-components=1 -xf - -C "$restore_target"
else
7z x -o"$restore_target" "$archive"
fi
elif [[ "$archive" == *.zst ]]; then
echo "π¦ Extracting .zst archive..."
if command -v pv >/dev/null; then
zstd -dc "$archive" | pv | tar --strip-components=1 -xf - -C "$restore_target"
else
zstd -dc "$archive" | tar -xf - -C "$restore_target"
fi
else
echo "π¦ Extracting .tar archive..."
if command -v pv >/dev/null; then
tar --strip-components=1 -xf - -C "$restore_target" < <(pv "$archive")
else
tar -xf "$archive" -C "$restore_target"
fi
fi
done
echo -e "\nβ
Restore complete"
# Restart Plex if it was stopped
if [ "$test_restore_flag" != "true" ]; then
read -rp "Would you like to start Plex now? (yes/no): " start_plex_confirm
if [[ "$start_plex_confirm" =~ ^[Yy](es)?$ ]]; then
if [ "$plex_type" == "docker" ]; then
echo "π Restarting Plex (Docker)..."
docker start plex >> /dev/null
elif [ "$plex_type" == "systemctl" ]; then
echo "π Restarting Plex (systemd)..."
systemctl start plexmediaserver
fi
else
echo "βΈοΈ Plex restart skipped."
fi
else
echo "π§ͺ Test restore: skipping Plex restart"
fi
[ "$test_restore_flag" == "true" ] && echo "π§ͺ Files restored to test directory: $restore_target"
}
## Main logic controller for backup operations
main() {
# Handle --help flag early and exit if needed
for arg in "$@"; do
if [[ "$arg" == "-h" || "$arg" == "--help" ]]; then
display_help
exit 0
fi
done
# Parse CLI arguments
handle_options "$@"
# Load config file if enabled
config_dir_setup
log_dir="$script_path/logs"
mkdir -p "$log_dir"
# Rotate old logs (keep only the 10 most recent)
ls -tp "$log_dir"/plex_backup_*.log 2>/dev/null | grep -v '/$' | tail -n +11 | xargs -r rm --
LOG_FILE="$log_dir/plex_backup_$(date +%F@%H.%M).log"
# exec > >(tee -a "$log_file") 2>&1
[ "$use_config_file" == "true" ] && load_config_file
if [ "$restore_flag" == "true" ] || [ "$test_restore_flag" == "true" ]; then
run_restore
[[ "${debug,,}" == "true" ]] && debug_output_function
exit 0
fi
# If dry run enabled, print a notice
[ "$dry_run" == "true" ] && log "π§ͺ Dry run mode enabled β simulation only"
# Convert hex color to decimal
hex_to_decimal "$bar_color"
# Validate directories and webhook
check_config "$@"
# Determine last backup date
last_plex_backup="$config_dir/.last_plex_backup.tmp"
[ -f "$last_plex_backup" ] && lastbackup=$(cat "$last_plex_backup") || lastbackup=0
current_date=$(date +"%m/%d/%y")
days=$((($(date --date="$current_date" +%s) - $(date --date="$lastbackup" +%s)) / (60 * 60 * 24)))
start=$(date +%s)
# Stop Plex if configured
get_plex_type
stop_plex
# Run Essential backup (and conditionally Full)
if [[ "${full_backup,,}" == "false" ]]; then
backup_type="essential"
create_backup "Essential"
build_payload
field_builder "Runtime" "$run_output" "true"
field_builder "This Essential backup size" "$essential_backup_size" "false"
field_builder "Total size of all Essential backups" "$essential_backup_total_size" "false"
payload "Essential Backup"
send_notification
if [ "$force_full_backup" != 0 ] && { [ "$days" -ge "$force_full_backup" ] || [ "$lastbackup" == 0 ]; }; then
backup_type="both"
create_backup "Full"
build_payload
field_builder "Runtime" "$run_output" "true"
field_builder "This Full backup size" "$full_backup_size" "false"
field_builder "Total size of all Full backups" "$full_backup_total_size" "false"
payload "Full Backup"
send_notification
days="0"
echo "$current_date" > "$last_plex_backup"
else
backup_type="essential_no_full"
log "π Skipping full backup (only $days days since last)"
fi
else
# Or just run Full backup
backup_type="full"
create_backup "Full"
[ "$backup_failed" == "true" ] && return
build_payload
field_builder "Runtime" "$run_output" "true"
field_builder "This Essential backup size" "$essential_backup_size" "false"
field_builder "This Full backup size" "$full_backup_size" "false"
field_builder "Total size of all Essential backups" "$essential_backup_total_size" "false"
field_builder "Total size of all Full backups" "$full_backup_total_size" "false"
field_builder "Days since last Full backup" "$days" "false"
payload "Full and Essential Backup"
send_notification
echo "$current_date" > "$last_plex_backup"
days="0"
fi
# Start Plex back up if needed
start_plex
# Clean up old backups
cleanup_function
# Print summary and optionally notify or debug
[[ "${unraid_notify,,}" == "true" ]] && unraid_notification
[[ "${debug,,}" == "true" ]] && debug_output_function
log "\n==================== β
Backup Summary ===================="
log "$(printf "π %-30s %s" "Backup Type:" "$backup_type")"
log "$(printf "β±οΈ %-30s %s" "Runtime:" "$run_output")"
log "$(printf "π %-30s %s" "Source Directory:" "$source_dir")"
log "$(printf "πΎ %-30s %s" "Destination Directory:" "$destination_dir")"
if [[ "$backup_type" =~ essential|both|essential_no_full ]]; then
log "$(printf "π§© %-30s %s" "Essential Size:" "$essential_backup_size")"
log "$(printf "π %-30s %s" "Total Essential Backups:" "$essential_backup_total_size")"
fi
if [[ "$backup_type" =~ full|both ]]; then
log "$(printf "ποΈ %-30s %s" "Full Size:" "$full_backup_size")"
log "$(printf "π¦ %-30s %s" "Total Full Backups:" "$full_backup_total_size")"
fi
log "$(printf "ποΈ %-30s %s" "Days Since Last Full:" "$days")"
if [[ "${full_backup,,}" == "false" && "$force_full_backup" -ne 0 ]]; then
next_full=$(( force_full_backup - days ))
if (( next_full > 0 )); then
log "$(printf "π
%-30s in %s day(s)" "Next Full Backup:" "$next_full")"
else
log "$(printf "π
%-30s %s" "Next Full Backup:" "Today (forced by schedule)")"
fi
fi
log "$(printf "π§ͺ %-30s %s" "Dry Run Mode:" "$dry_run")"
[[ "$backup_failed" == "true" ]] && log "\nβ οΈ Backup verification failed. Please review the logs."
log "==========================================================="
log "β
All Done!"
}
# Kick off the script with all passed arguments
main "$@"