-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathDBRepair.sh
executable file
·2363 lines (1886 loc) · 68.3 KB
/
DBRepair.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/sh
#########################################################################
# Plex Media Server database check and repair utility script. #
# Maintainer: ChuckPa #
# Version: v1.10.02 #
# Date: 03-Jan-2025 #
#########################################################################
# Version for display purposes
Version="v1.10.02"
# Have the databases passed integrity checks
CheckedDB=0
# By default, we cannot start/stop PMS
HaveStartStop=0
StartCommand=""
StopCommand=""
# By default, require root privilege
RootRequired=1
# By default, Errors are fatal.
IgnoreErrors=0
# By default, Duplicate view states not Removed
RemoveDuplicates=0
# Keep track of how many times the user's hit enter with no command (implied EOF)
NullCommands=0
# Default TMP dir for most hosts
TMPDIR="/tmp"
SYSTMP="/tmp"
# Global variable - main database
CPPL=com.plexapp.plugins.library
# Initial timestamp
TimeStamp="$(date "+%Y-%m-%d_%H.%M.%S")"
# Initialize global runtime variables
ManualConfig=0
CheckedDB=0
Damaged=0
DbPageSize=0
Fail=0
HaveStartStop=0
HostType=""
LOG_TOOL="echo"
ShowMenu=1
Exit=0
Scripted=0
HaveStartStop=0
# On all hosts except Mac
PIDOF="pidof"
STATFMT="-c"
STATBYTES="%s"
STATPERMS="%a"
# On all hosts except QNAP
DFFLAGS="-m"
# Universal output function
Output() {
if [ $Scripted -gt 0 ]; then
echo \[$(date "+%Y-%m-%d %H.%M.%S")\] "$@"
else
echo "$@"
fi
# $LOG_TOOL \[$(date "+%Y-%m-%d %H.%M.%S")\] "$@"
}
# Write to Repair Tool log
WriteLog() {
# Write given message into tool log file with TimeStamp
echo "$(date "+%Y-%m-%d %H.%M.%S") - $*" >> "$LOGFILE"
return 0
}
# Check given database file integrity
CheckDB() {
# Confirm the DB exists
[ ! -f "$1" ] && Output "ERROR: $1 does not exist." && return 1
# Now check database for corruption
Result="$("$PLEX_SQLITE" "$1" "PRAGMA integrity_check(1)")"
if [ "$Result" = "ok" ]; then
return 0
else
SQLerror="$(echo $Result | sed -e 's/.*code //')"
return 1
fi
}
# Check all databases
CheckDatabases() {
# Arg1 = calling function
# Arg2 = 'force' if present
# Check each of the databases. If all pass, set the 'CheckedDB' flag
# Only force recheck if flag given
# Check if not checked or forced
NeedCheck=0
[ $CheckedDB -eq 0 ] && NeedCheck=1
[ $CheckedDB -eq 1 ] && [ "$2" = "force" ] && NeedCheck=1
# Do we need to check
if [ $NeedCheck -eq 1 ]; then
# Clear Damaged flag
Damaged=0
CheckedDB=0
# Info
Output "Checking the PMS databases"
# Check main DB
if CheckDB $CPPL.db ; then
Output "Check complete. PMS main database is OK."
WriteLog "$1"" - Check $CPPL.db - PASS"
else
Output "Check complete. PMS main database is damaged."
WriteLog "$1"" - Check $CPPL.db - FAIL ($SQLerror)"
Damaged=1
fi
# Check blobs DB
if CheckDB $CPPL.blobs.db ; then
Output "Check complete. PMS blobs database is OK."
WriteLog "$1"" - Check $CPPL.blobs.db - PASS"
else
Output "Check complete. PMS blobs database is damaged."
WriteLog "$1"" - Check $CPPL.blobs.db - FAIL ($SQLerror)"
Damaged=1
fi
# Yes, we've now checked it
CheckedDB=1
fi
[ $Damaged -eq 0 ] && CheckedDB=1
# return status
return $Damaged
}
# Return list of database backup dates for consideration in replace action
GetDates(){
Dates=""
Tempfile="/tmp/DBRepairTool.$$.tmp"
touch "$Tempfile"
for i in $(find . -maxdepth 1 -name 'com.plexapp.plugins.library.db-????-??-??' | sort -r)
do
# echo Date - "${i//[^.]*db-/}"
Date="$(echo $i | sed -e 's/.*.db-//')"
# Only add if companion blobs DB exists
[ -e $CPPL.blobs.db-$Date ] && echo $Date >> "$Tempfile"
done
# Reload dates in sorted order
Dates="$(sort -r <$Tempfile)"
# Remove tempfile
rm -f "$Tempfile"
# Give results
echo $Dates
return
}
# Non-fatal SQLite error code check
SQLiteOK() {
# Global error variable
SQLerror=0
# Quick exit- known OK
[ $1 -eq 0 ] && return 0
# Put list of acceptable error codes here
Codes="19 28"
# By default assume the given code is an error
CodeError=1
for i in $Codes
do
if [ $i -eq $1 ]; then
CodeError=0
SQLerror=$i
break
fi
done
return $CodeError
}
# Perform a space check
# Store space available versus space needed in variables
# Return FAIL if needed GE available
# Arg 1, if provided, is multiplier
FreeSpaceAvailable() {
Multiplier=3
[ "$1" != "" ] && Multiplier=$1
# Available space where DB resides
SpaceAvailable=$(df $DFFLAGS "$AppSuppDir" | tail -1 | awk '{print $4}')
# Get size of DB and blobs, Minimally needing sum of both
LibSize="$(stat $STATFMT $STATBYTES "$CPPL.db")"
BlobsSize="$(stat $STATFMT $STATBYTES "$CPPL.blobs.db")"
SpaceNeeded=$((LibSize + BlobsSize))
# Compute need (minimum $Multiplier existing; current, backup, temp and room to write new)
SpaceNeeded=$(($SpaceNeeded * $Multiplier))
SpaceNeeded=$(($SpaceNeeded / 1000000))
# If need < available, all good
[ $SpaceNeeded -lt $SpaceAvailable ] && return 0
# Too close to call, fail
return 1
}
# Perform the actual copying for MakeBackup()
DoBackup() {
if [ -e $2 ]; then
cp -p "$2" "$3"
Result=$?
if [ $Result -ne 0 ]; then
Output "Error $Result while backing up '$2'. Cannot continue."
WriteLog "$1 - MakeBackup $2 - FAIL"
# Remove partial copied file and return
rm -f "$3"
return 1
else
WriteLog "$1 - MakeBackup $2 - PASS"
return 0
fi
fi
}
# Make a backup of the current database files and tag with TimeStamp
MakeBackups() {
Output "Backup current databases with '-BACKUP-$TimeStamp' timestamp."
for i in "db" "db-wal" "db-shm" "blobs.db" "blobs.db-wal" "blobs.db-shm"
do
DoBackup "$1" "${CPPL}.${i}" "$DBTMP/${CPPL}.${i}-BACKUP-$TimeStamp"
Result=$?
done
return $Result
}
ConfirmYesNo() {
Answer=""
while [ "$Answer" != "Y" ] && [ "$Answer" != "N" ]
do
printf "%s (Y/N) ? " "$1"
read Input
# EOF = No
case "$Input" in
YES|YE|Y|yes|ye|y)
Answer=Y
;;
NO|N|no|n)
Answer=N
;;
*)
Answer=""
;;
esac
# Unrecognized
if [ "$Answer" != "Y" ] && [ "$Answer" != "N" ]; then
echo \"$Input\" was not a valid reply. Please try again.
continue
fi
done
if [ "$Answer" = "Y" ]; then
# Confirmed Yes
return 0
else
return 1
fi
}
# Restore previously saved DB from given TimeStamp
RestoreSaved() {
T="$1"
for i in "db" "db-wal" "db-shm" "blobs.db" "blobs.db-wal" "blobs.db-shm"
do
[ -e "${CPPL}.${i}" ] && rm -f "${CPPL}.${i}"
[ -e "$DBTMP/${CPPL}.${i}-BACKUP-$T" ] && mv "$DBTMP/${CPPL}.${i}-BACKUP-$T" "${CPPL}.${i}"
done
}
# Return only the digits in the given version string
VersionDigits() {
local ver
ver=$(echo "$1" | tr -d [v\.] )
echo $ver
}
# Get the size of the given DB in MB
GetSize() {
Size=$(stat $STATFMT $STATBYTES "$1")
Size=$(expr $Size / 1048576)
[ $Size -eq 0 ] && Size=1
echo $Size
}
# Extract specified value from override file if it exists (Null if not)
GetOverride() {
Retval=""
# Don't know if we have pushd so do it long hand
CurrDir="$(pwd)"
# Find the metadata dir if customized
if [ -e /etc/systemd/system/plexmediaserver.service.d ]; then
# Get there
cd /etc/systemd/system/plexmediaserver.service.d
# Glob up all 'conf files' found
ConfFile="$(find override.conf local.conf *.conf 2>/dev/null | head -1)"
# If there is one, search it
if [ "$ConfFile" != "" ]; then
Retval="$(grep "$1" $ConfFile | head -1 | sed -e "s/.*${1}=//" | tr -d \" | tr -d \')"
fi
fi
# Go back to where we were
cd "$CurrDir"
# What did we find
echo "$Retval"
}
# Determine which host we are running on and set variables
HostConfig() {
# On all hosts except Mac
PIDOF="pidof"
STATFMT="-c"
STATBYTES="%s"
STATPERMS="%a"
# On all hosts except QNAP
DFFLAGS="-m"
# Manual Config
if [ $ManualConfig -eq 1 ]; then
CACHEDIR="$DBDIR/../../Cache/PhotoTranscoder"
LOGFILE="$DBDIR/DBRepair.log"
HostType="MANUAL"
return 0
fi
# Synology (DSM 7)
if [ -d /var/packages/PlexMediaServer ] && \
[ -d "/var/packages/PlexMediaServer/shares/PlexMediaServer/AppData/Plex Media Server" ]; then
# Where is the software
PKGDIR="/var/packages/PlexMediaServer/target"
PLEX_SQLITE="$PKGDIR/Plex SQLite"
LOG_TOOL="logger"
# Where is the data
AppSuppDir="/var/packages/PlexMediaServer/shares/PlexMediaServer/AppData"
DBDIR="$AppSuppDir/Plex Media Server/Plug-in Support/Databases"
CACHEDIR="$AppSuppDir/Plex Media Server/Cache/PhotoTranscoder"
PID_FILE="$AppSuppDir/Plex Media Server/plexmediaserver.pid"
LOGFILE="$DBDIR/DBRepair.log"
TMPDIR="$AppSuppDir/Plex Media Server/tmp"
SYSTMP="$TMPDIR"
# We are done
HostType="Synology (DSM 7)"
# We do have start/stop as root
HaveStartStop=1
StartCommand="/usr/syno/bin/synopkg start PlexMediaServer"
StopCommand="/usr/syno/bin/synopkg stop PlexMediaServer"
return 0
# Synology (DSM 6)
elif [ -d "/var/packages/Plex Media Server" ] && \
[ -f "/usr/syno/sbin/synoshare" ]; then
# Where is the software
PKGDIR="/var/packages/Plex Media Server/target"
PLEX_SQLITE="$PKGDIR/Plex SQLite"
LOG_TOOL="logger"
# Get shared folder path
AppSuppDir="$(synoshare --get Plex | grep Path | awk -F\[ '{print $2}' | awk -F\] '{print $1}')"
# Where is the data
AppSuppDir="$AppSuppDir/Library/Application Support"
if [ -d "$AppSuppDir/Plex Media Server" ]; then
DBDIR="$AppSuppDir/Plex Media Server/Plug-in Support/Databases"
CACHEDIR="$AppSuppDir/Plex Media Server/Cache/PhotoTranscoder"
PID_FILE="$AppSuppDir/Plex Media Server/plexmediaserver.pid"
LOGFILE="$DBDIR/DBRepair.log"
TMPDIR="$AppSuppDir/Plex Media Server/tmp"
SYSTMP="$TMPDIR"
HostType="Synology (DSM 6)"
# We do have start/stop as root
HaveStartStop=1
StartCommand="/usr/syno/bin/synopkg start PlexMediaServer"
StopCommand="/usr/syno/bin/synopkg stop PlexMediaServer"
return 0
fi
# QNAP (QTS & QuTS)
elif [ -f /etc/config/qpkg.conf ]; then
# Where is the software
PKGDIR="$(getcfg -f /etc/config/qpkg.conf PlexMediaServer Install_path)"
PLEX_SQLITE="$PKGDIR/Plex SQLite"
LOG_TOOL="/sbin/log_tool -t 0 -a"
# Where is the data
AppSuppDir="$PKGDIR/Library"
DBDIR="$AppSuppDir/Plex Media Server/Plug-in Support/Databases"
CACHEDIR="$AppSuppDir/Plex Media Server/Cache/PhotoTranscoder"
PID_FILE="$AppSuppDir/Plex Media Server/plexmediaserver.pid"
LOGFILE="$DBDIR/DBRepair.log"
TMPDIR="$AppSuppDir/tmp"
SYSTMP="$TMPDIR"
# Start/Stop
if [ -e /etc/init.d/plex.sh ]; then
HaveStartStop=1
StartCommand="/etc/init.d/plex.sh start"
StopCommand="/etc/init.d/plex.sh stop"
fi
# Use custom DFFLAGS (force POSIX mode)
DFFLAGS="-Pm"
HostType="QNAP"
return 0
# SNAP host (check before standard)
elif [ -d "/var/snap/plexmediaserver/common/Library/Application Support/Plex Media Server" ]; then
# Where things are
PLEX_SQLITE="/snap/plexmediaserver/current/Plex SQLite"
AppSuppDir="/var/snap/plexmediaserver/common/Library/Application Support"
CACHEDIR="$AppSuppDir/Plex Media Server/Cache/PhotoTranscoder"
PID_FILE="$AppSuppDir/plexmediaserver.pid"
DBDIR="$AppSuppDir/Plex Media Server/Plug-in Support/Databases"
LOGFILE="$DBDIR/DBRepair.log"
LOG_TOOL="logger"
TMPDIR="/var/snap/plexmediaserver/common/tmp"
SYSTMP="$TMPDIR"
HaveStartStop=1
StartCommand="snap start plexmediaserver"
StopCommand="snap stop plexmediaserver"
HostType="SNAP"
return 0
# Standard configuration Linux host
elif [ -f /etc/os-release ] && \
[ -d /usr/lib/plexmediaserver ] && \
[ -d /var/lib/plexmediaserver ]; then
# Where is the software
PKGDIR="/usr/lib/plexmediaserver"
PLEX_SQLITE="$PKGDIR/Plex SQLite"
LOG_TOOL="logger"
# Where is the data
AppSuppDir="/var/lib/plexmediaserver/Library/Application Support"
# DBDIR="$AppSuppDir/Plex Media Server/Plug-in Support/Databases"
# PID_FILE="$AppSuppDir/Plex Media Server/plexmediaserver.pid"
# Find the metadata dir if customized
if [ -e /etc/systemd/system/plexmediaserver.service.d ]; then
# Get custom AppSuppDir if specified
NewSuppDir="$(GetOverride PLEX_MEDIA_SERVER_APPLICATION_SUPPORT_DIR)"
if [ -d "$NewSuppDir" ]; then
AppSuppDir="$NewSuppDir"
else
Output "Given application support directory override specified does not exist: '$NewSuppDir'. Ignoring."
fi
fi
DBDIR="$AppSuppDir/Plex Media Server/Plug-in Support/Databases"
CACHEDIR="$AppSuppDir/Plex Media Server/Cache/PhotoTranscoder"
PID_FILE="$AppSuppDir/Plex Media Server/plexmediaserver.pid"
LOGFILE="$DBDIR/DBRepair.log"
HostType="$(grep ^PRETTY_NAME= /etc/os-release | sed -e 's/PRETTY_NAME=//' | sed -e 's/"//g')"
HaveStartStop=1
StartCommand="systemctl start plexmediaserver"
StopCommand="systemctl stop plexmediaserver"
TMPDIR="/tmp"
SYSTMP="$TMPDIR"
return 0
# Netgear ReadyNAS
elif [ -e /etc/os-release ] && [ "$(cat /etc/os-release | grep ReadyNASOS)" != "" ]; then
# Find PMS
if [ "$(echo /apps/plexmediaserver*)" != "/apps/plexmediaserver*" ]; then
PKGDIR="$(echo /apps/plexmediaserver*)"
# Where is the code
PLEX_SQLITE="$PKGDIR/Binaries/Plex SQLite"
AppSuppDir="$PKGDIR/MediaLibrary"
PID_FILE="$AppSuppDir/Plex Media Server/plexmediaserver.pid"
DBDIR="$AppSuppDir/Plex Media Server/Plug-in Support/Databases"
CACHEDIR="$AppSuppDir/Plex Media Server/Cache/PhotoTranscoder"
LOGFILE="$DBDIR/DBRepair.log"
LOG_TOOL="logger"
TMPDIR="$PKGDIR/temp"
SYSTMP="$TMPDIR"
HaveStartStop=1
StartCommand="systemctl start fvapp-plexmediaserver"
StopCommand="systemctl stop fvapp-plexmediaserver"
HostType="Netgear ReadyNAS"
return 0
fi
# ASUSTOR
elif [ -f /etc/nas.conf ] && grep ASUSTOR /etc/nas.conf >/dev/null && \
[ -d "/volume1/Plex/Library/Plex Media Server" ]; then
# Where are things
PLEX_SQLITE="/volume1/.@plugins/AppCentral/plexmediaserver/Plex SQLite"
AppSuppDir="/volume1/Plex/Library"
PID_FILE="$AppSuppDir/Plex Media Server/plexmediaserver.pid"
DBDIR="$AppSuppDir/Plex Media Server/Plug-in Support/Databases"
CACHEDIR="$AppSuppDir/Plex Media Server/Cache/PhotoTranscoder"
LOGFILE="$DBDIR/DBRepair.log"
LOG_TOOL="logger"
TMPDIR="/tmp"
SYSTMP="$TMPDIR"
HostType="ASUSTOR"
return 0
# Apple Mac
elif [ -d "/Applications/Plex Media Server.app" ] && \
[ -d "$HOME/Library/Application Support/Plex Media Server" ]; then
# Where is the software
PLEX_SQLITE="/Applications/Plex Media Server.app/Contents/MacOS/Plex SQLite"
AppSuppDir="$HOME/Library/Application Support"
DBDIR="$AppSuppDir/Plex Media Server/Plug-in Support/Databases"
CACHEDIR="$HOME/Library/Caches/PlexMediaServer/PhotoTranscoder"
LOGFILE="$DBDIR/DBRepair.log"
LOG_TOOL="logger"
TMPDIR="/tmp"
SYSTMP="$TMPDIR"
# MacOS uses pgrep and uses different stat options
PIDOF="pgrep"
STATFMT="-f"
STATBYTES="%z"
STATPERMS="%A"
# Root not required on MacOS. PMS runs as username.
RootRequired=0
# You can set haptic to 0 for silence.
HaveStartStop=1
StartCommand=startMacPMS
StopCommand=stopMacPMS
HapticOkay=1
HostType="Mac"
return 0
# Western Digital (OS5)
elif [ -f /etc/system.conf ] && [ -d /mnt/HD/HD_a2/Nas_Prog/plexmediaserver ] && \
grep "Western Digital Corp" /etc/system.conf >/dev/null; then
# Where things are
PLEX_SQLITE="/mnt/HD/HD_a2/Nas_Prog/plexmediaserver/binaries/Plex SQLite"
AppSuppDir="$(echo /mnt/HD/HD*/Nas_Prog/plex_conf)"
PID_FILE="$AppSuppDir/Plex Media Server/plexmediaserver.pid"
DBDIR="$AppSuppDir/Plex Media Server/Plug-in Support/Databases"
CACHEDIR="$AppSuppDir/Plex Media Server/Cache/PhotoTranscoder"
LOGFILE="$DBDIR/DBRepair.log"
LOG_TOOL="logger"
TMPDIR="$(dirname $AppSuppDir)/plexmediaserver/tmp_transcoding"
SYSTMP="$TMPDIR"
HostType="Western Digital"
return 0
# - Docker cgroup v1 & v2
# - Podman (libpod)
# - Kubernetes (and TrueNAS platforms)
elif [ "$(grep docker /proc/1/cgroup | wc -l)" -gt 0 ] || [ "$(grep 0::/ /proc/1/cgroup)" = "0::/" ] ||
[ "$(grep libpod /proc/1/cgroup | wc -l)" -gt 0 ] || [ "$(grep kube /proc/1/cgroup | wc -l)" -gt 0 ]; then
TMPDIR="/tmp"
SYSTMP="/tmp"
# HOTIO Plex image structure is non-standard (contains symlink which breaks detection)
if [ -n "$(grep -irslm 1 hotio /etc/s6-overlay/s6-rc.d)" ]; then
PLEX_SQLITE=$(find /app/bin/usr/lib/plexmediaserver /app/usr/lib/plexmediaserver /usr/lib/plexmediaserver -maxdepth 0 -type d -print -quit 2>/dev/null); PLEX_SQLITE="$PLEX_SQLITE/Plex SQLite"
AppSuppDir="/config"
PID_FILE="$AppSuppDir/plexmediaserver.pid"
DBDIR="$AppSuppDir/Plug-in Support/Databases"
CACHEDIR="$AppSuppDir/Plex Media Server/Cache/PhotoTranscoder"
LOGFILE="$DBDIR/DBRepair.log"
LOG_TOOL="logger"
if [ -d "/run/service/plex" ] || [ -d "/run/service/service-plex" ]; then
SERVICE_PATH=$([ -d "/run/service/plex" ] && echo "/run/service/plex" || [ -d "/run/service/service-plex" ] && echo "/run/service/service-plex")
HaveStartStop=1
StartCommand="s6-svc -u $SERVICE_PATH"
StopCommand="s6-svc -d $SERVICE_PATH"
fi
HostType="HOTIO"
return 0
# Docker (All main image variants except binhex and hotio)
elif [ -d "/config/Library/Application Support" ]; then
PLEX_SQLITE="/usr/lib/plexmediaserver/Plex SQLite"
AppSuppDir="/config/Library/Application Support"
PID_FILE="$AppSuppDir/Plex Media Server/plexmediaserver.pid"
DBDIR="$AppSuppDir/Plex Media Server/Plug-in Support/Databases"
CACHEDIR="$AppSuppDir/Plex Media Server/Cache/PhotoTranscoder"
LOGFILE="$DBDIR/DBRepair.log"
LOG_TOOL="logger"
# Miscellaneous start/stop methods
if [ -d "/var/run/service/svc-plex" ]; then
HaveStartStop=1
StartCommand="s6-svc -u /var/run/service/svc-plex"
StopCommand="s6-svc -d /var/run/service/svc-plex"
fi
if [ -d "/run/service/svc-plex" ]; then
HaveStartStop=1
StartCommand="s6-svc -u /run/service/svc-plex"
StopCommand="s6-svc -d /run/service/svc-plex"
fi
if [ -d "/var/run/s6/services/plex" ]; then
HaveStartStop=1
StartCommand="s6-svc -u /var/run/s6/services/plex"
StopCommand="s6-svc -d /var/run/s6/services/plex"
fi
HostType="Docker"
return 0
# BINHEX Plex image
elif [ -e /etc/os-release ] && grep "IMAGE_ID=archlinux" /etc/os-release 1>/dev/null && \
[ -e /home/nobody/start.sh ] && grep PLEX_MEDIA /home/nobody/start.sh 1> /dev/null ; then
PLEX_SQLITE="/usr/lib/plexmediaserver/Plex SQLite"
AppSuppDir="/config"
PID_FILE="$AppSuppDir/Plex Media Server/plexmediaserver.pid"
DBDIR="$AppSuppDir/Plex Media Server/Plug-in Support/Databases"
CACHEDIR="$AppSuppDir/Plex Media Server/Cache/PhotoTranscoder"
LOGFILE="$DBDIR/DBRepair.log"
LOG_TOOL="logger"
HostType="BINHEX"
return 0
fi
# Last chance to identify this host
elif [ -e /etc/os-release ]; then
# Arch Linux (must check for native Arch after binhex)
if [ "$(grep -E '=arch|="arch"' /etc/os-release)" != "" ] && \
[ -d /usr/lib/plexmediaserver ] && \
[ -d /var/lib/plex ]; then
# Where is the software
PKGDIR="/usr/lib/plexmediaserver"
PLEX_SQLITE="$PKGDIR/Plex SQLite"
LOG_TOOL="logger"
# Where is the data
AppSuppDir="/var/lib/plex"
# Find the metadata dir if customized
if [ -e /etc/systemd/system/plexmediaserver.service.d ]; then
# Get custom AppSuppDir if specified
NewSuppDir="$(GetOverride PLEX_MEDIA_SERVER_APPLICATION_SUPPORT_DIR)"
if [ "$NewSuppDir" != "" ]; then
if [ -d "$NewSuppDir" ]; then
AppSuppDir="$NewSuppDir"
else
Output "Given application support directory override specified does not exist: '$NewSuppDir'. Ignoring."
fi
fi
fi
DBDIR="$AppSuppDir/Plex Media Server/Plug-in Support/Databases"
CACHEDIR="$AppSuppDir/Plex Media Server/Cache/PhotoTranscoder"
LOGFILE="$DBDIR/DBRepair.log"
LOG_TOOL="logger"
TMPDIR="/tmp"
SYSTMP="/tmp"
HostType="$(grep PRETTY_NAME /etc/os-release | sed -e 's/^.*="//' | tr -d \" )"
HaveStartStop=1
StartCommand="systemctl start plexmediaserver"
StopCommand="systemctl stop plexmediaserver"
return 0
fi
fi
# Unknown / currently unsupported host
return 1
}
# Simple function to set variables
SetLast() {
LastName="$1"
LastTimestamp="$2"
return 0
}
##### INDEX
DoIndex() {
# Clear flag
Damaged=0
Fail=0
# Check databases before Indexing if not previously checked
if ! CheckDatabases "Reindex" ; then
Damaged=1
CheckedDB=1
Fail=1
[ $IgnoreErrors -eq 1 ] && Fail=0
fi
# If damaged, exit
if [ $Damaged -eq 1 ]; then
Output "Databases are damaged. Reindex operation not available. Please repair or replace first."
return
fi
# Databases are OK, Make a backup
Output "Backing up of databases"
MakeBackups "Reindex"
Result=$?
[ $IgnoreErrors -eq 1 ] && Result=0
if [ $Result -eq 0 ]; then
WriteLog "Reindex - MakeBackup - PASS"
else
Output "Error making backups. Cannot continue."
WriteLog "Reindex - MakeBackup - FAIL ($Result)"
Fail=1
return
fi
# Databases are OK, Start reindexing
Output "Reindexing main database"
"$PLEX_SQLITE" $CPPL.db 'REINDEX;'
Result=$?
[ $IgnoreErrors -eq 1 ] && Result=0
if SQLiteOK $Result; then
Output "Reindexing main database successful."
WriteLog "Reindex - Reindex: $CPPL.db - PASS"
else
Output "Reindexing main database failed. Error code $Result from Plex SQLite"
WriteLog "Reindex - Reindex: $CPPL.db - FAIL ($Result)"
Fail=1
fi
Output "Reindexing blobs database"
"$PLEX_SQLITE" $CPPL.blobs.db 'REINDEX;'
Result=$?
[ $IgnoreErrors -eq 1 ] && Result=0
if SQLiteOK $Result; then
Output "Reindexing blobs database successful."
WriteLog "Reindex - Reindex: $CPPL.blobs.db - PASS"
else
Output "Reindexing blobs database failed. Error code $Result from Plex SQLite"
WriteLog "Reindex - Reindex: $CPPL.blobs.db - FAIL ($Result)"
Fail=1
fi
Output "Reindex complete."
if [ $Fail -eq 0 ]; then
SetLast "Reindex" "$TimeStamp"
WriteLog "Reindex - PASS"
else
RestoreSaved "$TimeStamp"
WriteLog "Reindex - FAIL"
fi
return $Fail
}
##### UNDO
DoUndo(){
# Confirm there is something to undo
if [ "$LastTimestamp" != "" ]; then
# Educate user
echo ""
echo "'Undo' restores the databases to the state prior to the last SUCCESSFUL action."
echo "If any action fails before it completes, that action is automatically undone for you."
echo "Be advised: Undo restores the databases to their state PRIOR TO the last action of 'Vacuum', 'Reindex', or 'Replace'"
echo "WARNING: Once Undo completes, there will be nothing more to Undo untl another successful action is completed"
echo ""
if ConfirmYesNo "Undo '$LastName' performed at timestamp '$LastTimestamp' ? "; then
Output "Undoing $LastName ($LastTimestamp)"
for j in "db" "db-wal" "db-shm" "blobs.db" "blobs.db-wal" "blobs.db-shm"
do
[ -e "$TMPDIR/$CPPL.$j-BACKUP-$LastTimestamp" ] && mv -f "$TMPDIR/$CPPL.$j-BACKUP-$LastTimestamp" $CPPL.$j
done
Output "Undo complete."
WriteLog "Undo - Undo ${LastName}, TimeStamp $LastTimestamp"
SetLast "Undo" ""
fi
else
Output "Nothing to undo."
WriteLog "Undo - Nothing to Undo."
fi
}
##### DoSetPageSize
DoSetPageSize() {
# If DBREPAIR_PAGESIZE variable exists, validate it.
[ "$DBREPAIR_PAGESIZE" = "" ] && return
# Is it a valid positive integer ?
if [ "$DBREPAIR_PAGESIZE" != "$(echo "$DBREPAIR_PAGESIZE" | sed 's/[^0-9]*//g')" ]; then
WriteLog "SetPageSize - ERROR: DBREPAIR_PAGESIZE is not a valid integer. Ignoring '$DBREPAIR_PAGESIZE'"
Output "ERROR: DBREPAIR_PAGESIZE is not a valid integer. Ignoring '$DBREPAIR_PAGESIZE'"
return
fi
# Make certain it's a multiple of 1024 and gt 0
DbPageSize=$DBREPAIR_PAGESIZE
[ $DbPageSize -le 0 ] && return
if [ $(expr $DbPageSize % 1024) -ne 0 ]; then
DbPageSize=$(expr $DBREPAIR_PAGESIZE + 1023)
DbPageSize=$(expr $DbPageSize / 1024)
DbPageSize=$(expr $DbPageSize \* 1024)
WriteLog "DoSetPageSize - ERROR: DBREPAIR_PAGESIZE ($DBREPAIR_PAGESIZE) not a multiple of 1024. New value = $DbPageSize."
Output "WARNING: DBREPAIR_PAGESIZE ($DBREPAIR_PAGESIZE) not a multiple of 1024. New value = $DbPageSize."
fi
# Must be compliant
if [ $DbPageSize -gt 65536 ]; then
Output "WARNING: DBREPAIR_PAGESIZE ($DbPageSize) too large. Reducing to 65536."
WriteLog "SetPageSize - DBREPAIR_PAGESIZE ($DbPageSize) too large. Reducing."
DbPageSize=65536
fi
# Confirm a valid power of two.
IsPowTwo=0
for i in 1024 2048 4096 8192 16384 32768 65536
do
[ $i -eq $DbPageSize ] && IsPowTwo=1 && break
done
if [ $IsPowTwo -eq 0 ] && [ $DbPageSize -lt 65536 ]; then
for i in 1024 2048 4096 8192 16384 32768 65536
do
if [ $i -gt $DbPageSize ]; then
Output "ERROR: DBREPAIR_SIZE ($DbPageSize) not a power of 2 between 1024 and 65536. Value selected = $i."
WriteLog "SetPageSize - DBREPAIR_PAGESIZE ($DbPageSize) not a power of 2. New value selected = $i"
DbPageSize=$i
IsPowTwo=1
fi
[ $IsPowTwo -eq 1 ] && break
done
fi
Output "Setting Plex SQLite page size ($DbPageSize)"
WriteLog "SetPageSize - Setting Plex SQLite page_size: $DbPageSize"
# Create DB with desired page size
"$PLEX_SQLITE" "$1" "PRAGMA page_size=${DbPageSize}; VACUUM;"
}
##### DoRepair
DoRepair() {
Damaged=0
Fail=0
# Verify DBs are here
if [ ! -e $CPPL.db ]; then
Output "No main Plex database exists to repair. Exiting."
WriteLog "Repair - No main database - FAIL"
Fail=1
return 1
fi
# Check size
Size=$(stat $STATFMT $STATBYTES $CPPL.db)
# Exit if not valid
if [ $Size -lt 300000 ]; then
Output "Main database is too small/truncated, repair is not possible. Please try restoring a backup. "
WriteLog "Repair - Main databse too small - FAIL"
Fail=1
return 1
fi
# Continue
Output "Exporting current databases using timestamp: $TimeStamp"
Fail=0
# Attempt to export main db to SQL file (Step 1)
Output "Exporting Main DB"
"$PLEX_SQLITE" $CPPL.db ".output '$TMPDIR/library.plexapp.sql-$TimeStamp'" .dump
Result=$?
[ $IgnoreErrors -eq 1 ] && Result=0
if ! SQLiteOK $Result; then
# Cannot dump file
Output "Error $Result from Plex SQLite while exporting $CPPL.db"
Output "Could not successfully export the main database to repair it. Please try restoring a backup."
WriteLog "Repair - Cannot recover main database to '$TMPDIR/library.plexapp.sql-$TimeStamp' - FAIL ($Result)"
Fail=1
return 1
fi
# Attempt to export blobs db to SQL file
Output "Exporting Blobs DB"
"$PLEX_SQLITE" $CPPL.blobs.db ".output '$TMPDIR/blobs.plexapp.sql-$TimeStamp'" .dump
Result=$?
[ $IgnoreErrors -eq 1 ] && Result=0