Full Plex migration: preserve everything, no rebuild
Reverses the forward-only decision. That call predated measuring the library; at 27 TB / 25,148 video items / 337 GB of generated preview cache, rebuilding costs 1-3 weeks of saturated gigabit and permanently loses every manual match fix across 23,493 episodes. Migration preserves watch history, resume points, collections, playlists, manual matches, artwork choices, added-at dates, the 337 GB cache, and server identity - so shared users stay invited, clients do not re-add, and there is no claim step at all. migration/remap.sql Four path columns remapped: media_parts.file (80,126), section_locations .root_path (11 -> 9), media_streams.url (14,837) and metadata_items.guid (9). Two formats, not one: backslash/UNC for the first two, file:// with %20 encoding for the last two - decoding those %20s would break every subtitle reference containing a space, which given share names like Radio Shows is most of them. A scan of all 80 text columns across 82 tables found SIX columns matching korval. Only four are paths. taggings.text is one row reading Dr. Korval, and metadata_items.summary is four Liaden Universe blurbs about Clan Korval. A bare REPLACE on the word would have corrupted a cast credit and four book summaries, so every statement is anchored to a path prefix. Proven against a synthetic database built from the real path shapes: 12/12, including both false positives surviving byte-identical. Also drops the Audio Books and Music Organized roots - configured as library roots but holding 0 files / 0 bytes. The consolidation had already happened; only the dead roots remained. migration/migrate-db.sh Runs the remap through Plex own SQLite build borrowed from the container image, keeps a .pre-remap rollback, asserts the counts moved 1:1 and the false positives did not, then stats 200 random remapped paths against the real filesystem. That last check is the one that matters - SQL running without error proves nothing. migration/gen-preferences.ps1 Plex live settings store on Windows is the REGISTRY, not Preferences.xml, and the two disagree here. Folds ~50 values into one Linux file, dropping Windows-only keys including the per-GPU limit keyed by 10de:1b81, the GTX 1070 PCI ID. Preserves MachineIdentifier and the online token, which is what keeps the server identity. The existing Preferences.xml is malformed anyway (duplicate allowedNetworks) and will not parse strictly. scripts/20-cifs.sh Eight shares down to six. Mount points now mirror the share names verbatim - /mnt/nas/Home Movies, space and all - because that reduces the remap to one uniform prefix substitution instead of eleven special cases. New requirement this creates: \040 escaping in BOTH fstab fields, not just the share name. Verified, plus a round-trip check that a remapped DB path lands under the generated mount point. plex/docker-compose.yml Six read-only NAS binds whose source path equals target path, so database, host and container agree with no translation. No PLEX_CLAIM. Phase 2 Media relocation present but commented. scripts/60-media-relocate.sh Post-soak, optional: moves the 337 GB cache to the 3TB ext4 disk so future growth (~28 MB per content-hour) stops eating the SSD. Plex does not support this, so the script forces generation on one title afterwards to prove writes survive the EXDEV boundary, and rollback is deleting a compose override. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,200 @@
|
||||
# Plex Migration — Windows → Linux, nothing lost
|
||||
|
||||
Supersedes the earlier "forward-only, fresh Plex" decision. That call was made
|
||||
before the library was measured. At **27 TB, 25,148 video items and 337 GB of
|
||||
already-generated preview cache**, rebuilding fresh costs one to three weeks of
|
||||
saturated NAS link and permanently loses every manual match fix. Migration is
|
||||
the cheaper and lower-risk option.
|
||||
|
||||
## What survives
|
||||
|
||||
Watch history and resume points across all items, play counts, ratings,
|
||||
collections, playlists, every manual match correction, poster and artwork
|
||||
choices, added-at dates (so Recently Added stays meaningful), the 337 GB
|
||||
preview cache, and **the server identity** — shared users stay invited, clients
|
||||
do not need to re-add the server, and there is no claim step at all.
|
||||
|
||||
Plex's own article calls cross-OS moves "possible but not officially supported
|
||||
and not covered here." That is a documentation gap, not a technical barrier.
|
||||
The database is platform-independent; what Plex declines to help with is
|
||||
mapping the settings, which `gen-preferences.ps1` does.
|
||||
|
||||
## Facts everything below depends on
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | PMS **1.43.3.10828**, Windows 10, data dir `D:\Plex\Local Data` |
|
||||
| Server identity | `machineIdentifier eb69ec8a…` — preserved, not regenerated |
|
||||
| Data directory | ~374 GB total → ~364 GB after pruning |
|
||||
| Library | 1,360 movies · 23,493 episodes · 295 other video · 20,798 audio |
|
||||
| Path rows | 80,126 `media_parts` · 14,837 `media_streams` · 11 → 9 roots |
|
||||
| Target layout | Whole data dir on the 500 GB SSD (~75 GB free) |
|
||||
| NAS mounts | 6 shares at `/mnt/nas/<exact share name>` |
|
||||
|
||||
---
|
||||
|
||||
## M0 — Prepare, while Windows is still running
|
||||
|
||||
**Disable automatic trash emptying first.** This is step 1 of Plex's own
|
||||
procedure and it matters more here than usual: the registry confirms
|
||||
`autoEmptyTrash = 1`, and the new NAS account is read-write. A missing mount at
|
||||
scan time would mean Plex deletes library records it has permission to delete.
|
||||
Settings → Library → untick *Empty trash automatically after every scan*.
|
||||
|
||||
Generate the Linux settings file from the registry:
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File .\gen-preferences.ps1 -Out C:\mbx\Preferences.xml
|
||||
[xml](Get-Content -Raw C:\mbx\Preferences.xml) | Out-Null; 'XML OK'
|
||||
```
|
||||
|
||||
**Stop Plex Media Server completely** — tray icon → Exit, then confirm no
|
||||
`Plex Media Server.exe` remains. The database must not be open when copied, or
|
||||
the WAL will be mid-flight and the copy inconsistent.
|
||||
|
||||
Copy the data directory to the NAS. Skip what must not travel:
|
||||
|
||||
```powershell
|
||||
robocopy "D:\Plex\Local Data\Plex Media Server" "\\korval\Share\backups\mediabox\PMS" `
|
||||
/E /COPY:DAT /R:2 /W:5 /MT:16 `
|
||||
/XD "Cache" "Codecs" "Drivers" "Crash Reports" "Logs" "Updates" `
|
||||
/LOG:C:\mbx\pms-copy.log /TEE
|
||||
```
|
||||
|
||||
`Codecs` and `Drivers` are **Windows binaries** — copying them to Linux breaks
|
||||
transcoding. `Cache` is regenerable. Excluding them also trims the copy.
|
||||
|
||||
> **GATE M0** — robocopy reports 0 failures. `Plug-in Support\Databases\`,
|
||||
> `Metadata\` and `Media\` are all present on the NAS. **Do not proceed on a
|
||||
> copy you have not listed.**
|
||||
|
||||
---
|
||||
|
||||
## M1 — Dry run, before anything is destroyed
|
||||
|
||||
The whole migration can be rehearsed while Windows still works. This is the
|
||||
step that makes the rest safe.
|
||||
|
||||
On arrsstack (or any Linux host with the NAS mounted), take **only** the
|
||||
database and Preferences — a couple of GB, not 364 — and run the remap:
|
||||
|
||||
```bash
|
||||
sudo ./migrate-db.sh /path/to/copy/com.plexapp.plugins.library.db
|
||||
```
|
||||
|
||||
Then start a throwaway Plex against it **with no internet access**, so it
|
||||
cannot contact plex.tv and collide with the live server that shares its
|
||||
identity:
|
||||
|
||||
```bash
|
||||
docker network create --internal plex-dryrun
|
||||
docker run --rm -d --name plex-dryrun --network plex-dryrun \
|
||||
-v /path/to/dryrun-config:/config \
|
||||
-v "/mnt/nas/media:/mnt/nas/media:ro" \
|
||||
lscr.io/linuxserver/plex:latest
|
||||
```
|
||||
|
||||
> **GATE M1** — browse the unclaimed server directly and confirm: Movies shows
|
||||
> **1,360**, TV Shows shows **23,493 episodes**, watch state and resume points
|
||||
> are present, and a title's file path resolves. If this passes, the migration
|
||||
> is proven. If it fails you have lost an afternoon and nothing else.
|
||||
|
||||
---
|
||||
|
||||
## M2 — Install Linux
|
||||
|
||||
Follow the main `runbook.md` phases 2–5 (BIOS, USB, install, first boot). The
|
||||
autoinstall targets Disk 0 by serial `1808AE802176` and leaves the 3 TB disk
|
||||
untouched.
|
||||
|
||||
Write the NAS credentials and bring up the six mounts:
|
||||
|
||||
```bash
|
||||
printf 'username=mediabox\npassword=<pass>\ndomain=WORKGROUP\n' \
|
||||
| sudo tee /etc/cifs/korval.cred >/dev/null
|
||||
sudo chmod 600 /etc/cifs/korval.cred
|
||||
sudo systemctl daemon-reload
|
||||
sudo /srv/mediabox-bootstrap/scripts/20-cifs.sh --verify
|
||||
```
|
||||
|
||||
> **GATE M2** — all six mounts report `[ok]`, and `stat -c '%u:%g' /mnt/nas/media`
|
||||
> returns `3000:3000`. Wrong ownership means Plex hits permission errors on
|
||||
> every file.
|
||||
|
||||
---
|
||||
|
||||
## M3 — Restore and remap
|
||||
|
||||
```bash
|
||||
sudo install -d -o 3000 -g 3000 /srv/plex/config
|
||||
sudo rsync -a --info=progress2 \
|
||||
"/mnt/nas/Share/backups/mediabox/PMS/" \
|
||||
"/srv/plex/config/Library/Application Support/Plex Media Server/"
|
||||
|
||||
sudo install -o 3000 -g 3000 -m 0644 /path/to/Preferences.xml \
|
||||
"/srv/plex/config/Library/Application Support/Plex Media Server/Preferences.xml"
|
||||
|
||||
sudo /srv/mediabox-bootstrap/migration/migrate-db.sh \
|
||||
"/srv/plex/config/Library/Application Support/Plex Media Server/Plug-in Support/Databases/com.plexapp.plugins.library.db"
|
||||
|
||||
sudo chown -R 3000:3000 /srv/plex/config
|
||||
```
|
||||
|
||||
`migrate-db.sh` keeps a `.pre-remap` rollback copy, asserts that no Windows
|
||||
paths remain, that the counts moved 1:1, that the "Dr. Korval" tag and the four
|
||||
Liaden book summaries are **untouched**, and finally stats 200 random remapped
|
||||
paths against the real filesystem.
|
||||
|
||||
> **GATE M3** — `migrate-db.sh` exits 0 with the sample check reporting
|
||||
> `200/200 sampled files resolve on disk`. That last line is the one that
|
||||
> matters; SQL running without error proves nothing.
|
||||
|
||||
---
|
||||
|
||||
## M4 — First start
|
||||
|
||||
```bash
|
||||
sudo RENDER_GID=$(stat -c '%g' /dev/dri/renderD128) \
|
||||
/srv/mediabox-bootstrap/scripts/50-plex.sh
|
||||
```
|
||||
|
||||
No claim token. The server already has its identity.
|
||||
|
||||
> **GATE M4** — `plex.thewichersfamily.com` loads and shows *Magi Plex* with
|
||||
> your libraries. Watch history and Continue Watching are intact. A remote
|
||||
> client that already had this server still sees it without re-adding.
|
||||
> Play something and confirm `intel_gpu_top` shows the video engine working.
|
||||
|
||||
---
|
||||
|
||||
## M5 — Soak
|
||||
|
||||
One to two weeks on the supported layout. Confirm mounts survive a NAS reboot,
|
||||
the GPU survives a kernel update, and the box comes back **unattended** from a
|
||||
real power cut. That last one is the acceptance test for "headless".
|
||||
|
||||
---
|
||||
|
||||
## M6 — Relocate the preview cache (optional, post-soak)
|
||||
|
||||
Only after M5. Moves the 337 GB `Media/` directory to the 3 TB ext4 disk so
|
||||
future thumbnail growth (~28 MB per content-hour) stops consuming the SSD.
|
||||
|
||||
```bash
|
||||
sudo /srv/mediabox-bootstrap/scripts/60-media-relocate.sh
|
||||
```
|
||||
|
||||
Plex does **not** support relocating this directory. The script performs the
|
||||
move, enables the bind mount, and then forces thumbnail generation on a single
|
||||
title to prove writes succeed across the filesystem boundary — the one failure
|
||||
mode that cannot be reasoned about, only tested. Rollback is moving it back.
|
||||
|
||||
---
|
||||
|
||||
## If something goes wrong
|
||||
|
||||
Before M2, everything is reversible — Windows still boots. After M2 the
|
||||
recovery path is *reinstall*, not *roll back*: the USB rebuilds the box in
|
||||
about twenty minutes and the data directory is still on the NAS. The database
|
||||
copy on the NAS outlives every step here, and `migrate-db.sh` leaves a
|
||||
`.pre-remap` copy beside every database it touches.
|
||||
@@ -0,0 +1,110 @@
|
||||
<#
|
||||
================================================================================
|
||||
gen-preferences.ps1 — build a Linux Preferences.xml from the Windows registry
|
||||
|
||||
Run ON THE WINDOWS BOX, before it is wiped. Read-only: it does not modify the
|
||||
registry or the running server.
|
||||
|
||||
powershell -ExecutionPolicy Bypass -File .\gen-preferences.ps1 -Out C:\mbx\Preferences.xml
|
||||
|
||||
WHY THIS EXISTS
|
||||
On Windows, Plex's live settings store is the REGISTRY
|
||||
(HKCU\SOFTWARE\Plex, Inc.\Plex Media Server), not Preferences.xml. The two
|
||||
disagree on this install — the on-disk Preferences.xml was last written in
|
||||
2021 and is missing settings the registry has. Linux has no registry, so
|
||||
everything must be folded into a single Preferences.xml. This is the
|
||||
"mapping the additional server settings" that Plex's own migration article
|
||||
calls complicated and declines to cover.
|
||||
|
||||
It also rebuilds the file cleanly, which is required anyway: the existing
|
||||
Preferences.xml is malformed (duplicate allowedNetworks attribute) and will
|
||||
not parse with a strict XML parser.
|
||||
|
||||
WHAT IS PRESERVED
|
||||
MachineIdentifier, ProcessedMachineIdentifier, CertificateUUID and the
|
||||
online token carry across. Those are what keep your server IDENTITY — shared
|
||||
users stay invited, clients do not need to re-add the server.
|
||||
|
||||
Secrets are written to the output file but never printed to the console.
|
||||
================================================================================
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$Out = "$PSScriptRoot\Preferences.xml",
|
||||
[string]$TranscodeDir = "/transcode"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$key = 'HKCU:\SOFTWARE\Plex, Inc.\Plex Media Server'
|
||||
if (-not (Test-Path $key)) { throw "registry key not found: $key" }
|
||||
|
||||
# --- keys that are meaningless or harmful on Linux ---------------------------
|
||||
$drop = @(
|
||||
'InstallFolder' # C:\Program Files\... — Windows path
|
||||
'LocalAppDataPath' # D:\Plex\Local Data — Windows path
|
||||
'PreferredNetworkInterface' # a Windows adapter GUID
|
||||
'LastAutomaticMappedPort' # regenerated on first run
|
||||
'PubSubServer' # regenerated; the Ping value is a byte array
|
||||
'PubSubServerPing'
|
||||
'PubSubServerRegion'
|
||||
'CloudSyncNeedsUpdate'
|
||||
)
|
||||
# Per-GPU transcode limits are keyed by PCI vendor:device. 10de:1b81 is the
|
||||
# GTX 1070. Meaningless once the GPU is addressed through /dev/dri or the
|
||||
# NVIDIA container runtime.
|
||||
$dropPattern = '^_[0-9a-f]{16}-'
|
||||
|
||||
# --- keys we deliberately override -------------------------------------------
|
||||
$override = @{
|
||||
# Step 1 of Plex's own migration procedure, and doubly important here: the
|
||||
# NAS account is read-write, so a missing mount at scan time plus this
|
||||
# setting means Plex deletes library records it has permission to delete.
|
||||
'autoEmptyTrash' = '0'
|
||||
# Windows path -> the tmpfs mount defined in the compose file.
|
||||
'TranscoderTempDirectory' = $TranscodeDir
|
||||
}
|
||||
|
||||
$props = Get-ItemProperty $key
|
||||
$pairs = [ordered]@{}
|
||||
|
||||
foreach ($p in ($props.PSObject.Properties | Where-Object { $_.Name -notmatch '^PS' } | Sort-Object Name)) {
|
||||
$n = $p.Name
|
||||
if ($drop -contains $n) { continue }
|
||||
if ($n -match $dropPattern) { continue }
|
||||
$v = $p.Value
|
||||
if ($v -is [byte[]]) { continue } # not representable as an attribute
|
||||
$pairs[$n] = [string]$v
|
||||
}
|
||||
|
||||
foreach ($k in $override.Keys) { $pairs[$k] = $override[$k] }
|
||||
|
||||
# --- emit ---------------------------------------------------------------------
|
||||
$sb = New-Object System.Text.StringBuilder
|
||||
[void]$sb.AppendLine('<?xml version="1.0" encoding="utf-8"?>')
|
||||
[void]$sb.Append('<Preferences')
|
||||
foreach ($k in $pairs.Keys) {
|
||||
$esc = [System.Security.SecurityElement]::Escape($pairs[$k])
|
||||
[void]$sb.Append(" $k=`"$esc`"")
|
||||
}
|
||||
[void]$sb.AppendLine('/>')
|
||||
|
||||
# UTF-8 WITHOUT BOM. A BOM here is the same class of bug that silently breaks
|
||||
# administrators_authorized_keys on Windows OpenSSH.
|
||||
[System.IO.File]::WriteAllText($Out, $sb.ToString(), (New-Object System.Text.UTF8Encoding($false)))
|
||||
|
||||
# --- report: NAMES ONLY, never values ----------------------------------------
|
||||
$secretish = '(Token|Identifier|UUID|GracenoteUser|Mail)'
|
||||
Write-Host "wrote $Out ($($pairs.Count) settings)"
|
||||
Write-Host ""
|
||||
Write-Host "carried across:"
|
||||
$pairs.Keys | Where-Object { $_ -match $secretish } | ForEach-Object { Write-Host " $_ <redacted>" }
|
||||
Write-Host ""
|
||||
Write-Host "overridden:"
|
||||
$override.Keys | ForEach-Object { Write-Host (" {0} = {1}" -f $_, $override[$_]) }
|
||||
Write-Host ""
|
||||
Write-Host "dropped (Windows-only):"
|
||||
$drop | ForEach-Object { Write-Host " $_" }
|
||||
Write-Host " <per-GPU transcode limit keys>"
|
||||
Write-Host ""
|
||||
Write-Host "Verify it parses before you rely on it:"
|
||||
Write-Host " [xml](Get-Content -Raw '$Out') | Out-Null; 'XML OK'"
|
||||
Executable
+162
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env bash
|
||||
# ============================================================================
|
||||
# migrate-db.sh — apply the path remap to a COPY of the Plex database and
|
||||
# prove it worked.
|
||||
#
|
||||
# Usage:
|
||||
# sudo ./migrate-db.sh /path/to/com.plexapp.plugins.library.db [PLEX_IMAGE]
|
||||
#
|
||||
# This script NEVER touches a live database. It operates on the file you hand
|
||||
# it, which must already be a copy taken from a stopped server or one of
|
||||
# Plex's own dated backups.
|
||||
#
|
||||
# It uses Plex's own SQLite build, borrowed from the Plex container image, so
|
||||
# nothing has to be installed on the host and stock sqlite3 is never involved.
|
||||
#
|
||||
# The final check is the one that actually matters: it takes a random sample
|
||||
# of remapped paths and stats them on disk. SQL that runs without error proves
|
||||
# nothing; files that open prove everything.
|
||||
# ============================================================================
|
||||
set -uo pipefail
|
||||
|
||||
DB="${1:?usage: migrate-db.sh <path-to-library.db> [plex-image]}"
|
||||
IMAGE="${2:-lscr.io/linuxserver/plex:latest}"
|
||||
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
SAMPLE=200
|
||||
|
||||
[ -f "$DB" ] || { echo "no such database: $DB"; exit 1; }
|
||||
|
||||
DBDIR="$(cd "$(dirname "$DB")" && pwd)"
|
||||
DBNAME="$(basename "$DB")"
|
||||
|
||||
PASS=0; FAIL=0
|
||||
ok(){ printf ' \033[1;32m[pass]\033[0m %s\n' "$*"; PASS=$((PASS+1)); }
|
||||
bad(){ printf ' \033[1;31m[FAIL]\033[0m %s\n' "$*"; FAIL=$((FAIL+1)); }
|
||||
note(){ printf ' %s\n' "$*"; }
|
||||
|
||||
# Run a query through Plex's SQLite inside a throwaway container.
|
||||
psql() {
|
||||
docker run --rm -i \
|
||||
-v "$DBDIR:/db" \
|
||||
-v "$HERE:/migration:ro" \
|
||||
--entrypoint "/usr/lib/plexmediaserver/Plex SQLite" \
|
||||
"$IMAGE" "/db/$DBNAME" "$@" 2>/dev/null
|
||||
}
|
||||
|
||||
echo "=== database: $DB"
|
||||
echo "=== image: $IMAGE"
|
||||
echo
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# BEFORE — capture the baseline
|
||||
# ---------------------------------------------------------------------------
|
||||
echo "--- baseline (Windows paths present) ---"
|
||||
B_PARTS=$(psql "SELECT COUNT(*) FROM media_parts WHERE file LIKE '\\\\korval\\%';")
|
||||
B_ROOTS=$(psql "SELECT COUNT(*) FROM section_locations WHERE root_path LIKE '\\\\korval\\%';")
|
||||
B_STREAMS=$(psql "SELECT COUNT(*) FROM media_streams WHERE url LIKE 'file://korval/%';")
|
||||
B_GUIDS=$(psql "SELECT COUNT(*) FROM metadata_items WHERE guid LIKE 'file://korval/%';")
|
||||
B_TAG=$(psql "SELECT COUNT(*) FROM taggings WHERE text LIKE '%Korval%';")
|
||||
B_SUM=$(psql "SELECT COUNT(*) FROM metadata_items WHERE summary LIKE '%Korval%';")
|
||||
note "media_parts.file $B_PARTS"
|
||||
note "section_locations.root_path $B_ROOTS"
|
||||
note "media_streams.url $B_STREAMS"
|
||||
note "metadata_items.guid $B_GUIDS"
|
||||
note "taggings.text (NOT a path) $B_TAG <- must survive untouched"
|
||||
note "metadata_items.summary $B_SUM <- must survive untouched"
|
||||
|
||||
if [ "${B_PARTS:-0}" -eq 0 ]; then
|
||||
echo
|
||||
echo " Nothing to remap — this database has no Windows paths left."
|
||||
echo " (Already migrated? Wrong file?)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# REMAP
|
||||
# ---------------------------------------------------------------------------
|
||||
echo
|
||||
echo "--- applying remap.sql ---"
|
||||
cp -a "$DB" "${DB}.pre-remap" && note "rollback copy: ${DB}.pre-remap"
|
||||
if psql ".read /migration/remap.sql"; then
|
||||
note "remap applied"
|
||||
else
|
||||
bad "remap.sql failed — restore from ${DB}.pre-remap"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# AFTER — assert
|
||||
# ---------------------------------------------------------------------------
|
||||
echo
|
||||
echo "--- verification ---"
|
||||
|
||||
A_WINPARTS=$(psql "SELECT COUNT(*) FROM media_parts WHERE file LIKE '\\\\korval\\%';")
|
||||
A_WINROOTS=$(psql "SELECT COUNT(*) FROM section_locations WHERE root_path LIKE '\\\\korval\\%';")
|
||||
A_WINSTRM=$(psql "SELECT COUNT(*) FROM media_streams WHERE url LIKE 'file://korval/%';")
|
||||
A_WINGUID=$(psql "SELECT COUNT(*) FROM metadata_items WHERE guid LIKE 'file://korval/%';")
|
||||
|
||||
[ "$A_WINPARTS" = 0 ] && ok "no Windows paths left in media_parts" || bad "media_parts still has $A_WINPARTS Windows paths"
|
||||
[ "$A_WINROOTS" = 0 ] && ok "no Windows paths left in section_locations" || bad "section_locations still has $A_WINROOTS"
|
||||
[ "$A_WINSTRM" = 0 ] && ok "no Windows URLs left in media_streams" || bad "media_streams still has $A_WINSTRM"
|
||||
[ "$A_WINGUID" = 0 ] && ok "no Windows URLs left in metadata_items.guid" || bad "metadata_items.guid still has $A_WINGUID"
|
||||
|
||||
A_PARTS=$(psql "SELECT COUNT(*) FROM media_parts WHERE file LIKE '/mnt/nas/%';")
|
||||
A_STREAMS=$(psql "SELECT COUNT(*) FROM media_streams WHERE url LIKE 'file:///mnt/nas/%';")
|
||||
A_GUIDS=$(psql "SELECT COUNT(*) FROM metadata_items WHERE guid LIKE 'file:///mnt/nas/%';")
|
||||
A_ROOTS=$(psql "SELECT COUNT(*) FROM section_locations WHERE root_path LIKE '/mnt/nas/%';")
|
||||
|
||||
[ "$A_PARTS" = "$B_PARTS" ] && ok "media_parts remapped 1:1 ($A_PARTS)" || bad "media_parts $B_PARTS -> $A_PARTS"
|
||||
[ "$A_STREAMS" = "$B_STREAMS" ] && ok "media_streams remapped 1:1 ($A_STREAMS)" || bad "media_streams $B_STREAMS -> $A_STREAMS"
|
||||
[ "$A_GUIDS" = "$B_GUIDS" ] && ok "metadata_items.guid remapped 1:1" || bad "guid $B_GUIDS -> $A_GUIDS"
|
||||
# roots: 11 in, 9 out — the two empty legacy roots are deliberately deleted
|
||||
[ "$A_ROOTS" = 9 ] && ok "9 library roots (2 empty legacy roots dropped)" || bad "expected 9 roots, got $A_ROOTS"
|
||||
|
||||
# --- the false positives must be untouched --------------------------------
|
||||
A_TAG=$(psql "SELECT COUNT(*) FROM taggings WHERE text LIKE '%Korval%';")
|
||||
A_SUM=$(psql "SELECT COUNT(*) FROM metadata_items WHERE summary LIKE '%Korval%';")
|
||||
[ "$A_TAG" = "$B_TAG" ] && ok "taggings.text untouched ($A_TAG row, 'Dr. Korval')" || bad "taggings.text changed: $B_TAG -> $A_TAG"
|
||||
[ "$A_SUM" = "$B_SUM" ] && ok "metadata_items.summary untouched ($A_SUM Liaden blurbs)" || bad "summary changed: $B_SUM -> $A_SUM"
|
||||
|
||||
# --- no double-encoding or mangled separators ------------------------------
|
||||
BAD_SEP=$(psql "SELECT COUNT(*) FROM media_parts WHERE file LIKE '%\\%';")
|
||||
[ "$BAD_SEP" = 0 ] && ok "no backslashes remain in media_parts.file" || bad "$BAD_SEP rows still contain a backslash"
|
||||
BAD_PCT=$(psql "SELECT COUNT(*) FROM media_parts WHERE file LIKE '%|%20%';")
|
||||
[ "${BAD_PCT:-0}" = 0 ] && ok "no %20 leaked into filesystem paths" || bad "$BAD_PCT rows have %20 in a filesystem path"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# THE REAL TEST — do the remapped paths open?
|
||||
# ---------------------------------------------------------------------------
|
||||
echo
|
||||
echo "--- resolving $SAMPLE random remapped paths against the filesystem ---"
|
||||
if ! mountpoint -q /mnt/nas/media 2>/dev/null; then
|
||||
note "SKIPPED: /mnt/nas/media is not mounted. Mount the NAS and re-run:"
|
||||
note " $0 $DB"
|
||||
else
|
||||
found=0; missing=0; shown=0
|
||||
while IFS= read -r p; do
|
||||
[ -z "$p" ] && continue
|
||||
if [ -e "$p" ]; then
|
||||
found=$((found+1))
|
||||
else
|
||||
missing=$((missing+1))
|
||||
if [ "$shown" -lt 5 ]; then note "MISSING: $p"; shown=$((shown+1)); fi
|
||||
fi
|
||||
done < <(psql "SELECT file FROM media_parts WHERE file LIKE '/mnt/nas/%' ORDER BY RANDOM() LIMIT $SAMPLE;")
|
||||
|
||||
total=$((found+missing))
|
||||
if [ "$total" -gt 0 ] && [ "$missing" -eq 0 ]; then
|
||||
ok "$found/$total sampled files resolve on disk"
|
||||
else
|
||||
bad "$missing/$total sampled files DO NOT resolve — remap or mounts are wrong"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "=== $PASS passed, $FAIL failed ==="
|
||||
if [ "$FAIL" -eq 0 ]; then
|
||||
echo "Database is ready. Rollback copy kept at ${DB}.pre-remap"
|
||||
exit 0
|
||||
else
|
||||
echo "DO NOT USE THIS DATABASE. Restore: mv ${DB}.pre-remap $DB"
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,128 @@
|
||||
-- ============================================================================
|
||||
-- mediabox — Plex library path remap: Windows UNC -> Linux mount paths
|
||||
--
|
||||
-- RUN WITH "Plex SQLite", NOT stock sqlite3.
|
||||
-- Plex ships its own SQLite build with specific compile options.
|
||||
-- Windows: "C:\Program Files\Plex\Plex Media Server\Plex SQLite.exe"
|
||||
-- Linux: /usr/lib/plexmediaserver/Plex\ SQLite
|
||||
-- Stock sqlite3 may refuse to open it, or worse, open it and corrupt it.
|
||||
--
|
||||
-- RUN ON A COPY. Never against a database a server has open. Use either a
|
||||
-- copy taken from a cleanly STOPPED server, or one of Plex's own dated
|
||||
-- backups (com.plexapp.plugins.library.db-YYYY-MM-DD), which are already
|
||||
-- consistent snapshots.
|
||||
--
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- VERIFIED AGAINST THE LIVE LIBRARY 2026-07-27
|
||||
--
|
||||
-- Every text column in all 82 tables was scanned for the string 'korval'.
|
||||
-- Six columns matched. Only FOUR of them are paths:
|
||||
--
|
||||
-- media_parts.file 80,126 rows backslash / UNC form
|
||||
-- section_locations.root_path 11 rows backslash / UNC form
|
||||
-- media_streams.url 14,837 rows file:// form, %20-encoded
|
||||
-- metadata_items.guid 9 rows file:// form, %20-encoded
|
||||
--
|
||||
-- TWO COLUMNS MATCH THE WORD BUT ARE NOT PATHS AND MUST NEVER BE TOUCHED:
|
||||
--
|
||||
-- taggings.text 1 row — "Dr. Korval", a credited person
|
||||
-- metadata_items.summary 4 rows — Liaden Universe book blurbs that
|
||||
-- mention "Clan Korval"
|
||||
--
|
||||
-- This is why every statement below is anchored to a PATH PREFIX
|
||||
-- ('\\korval\' or 'file://korval/') and never to the bare word. A naive
|
||||
-- REPLACE(col,'korval',...) across matching columns would silently corrupt
|
||||
-- four book summaries and a cast credit.
|
||||
-- ---------------------------------------------------------------------------
|
||||
--
|
||||
-- MOUNT CONTRACT — this SQL assumes each NAS share is mounted at
|
||||
-- /mnt/nas/<exact share name>, capitalisation and spaces preserved:
|
||||
--
|
||||
-- //10.0.1.254/media -> /mnt/nas/media
|
||||
-- //10.0.1.254/Radio Shows -> /mnt/nas/Radio Shows
|
||||
-- //10.0.1.254/Education Videos -> /mnt/nas/Education Videos
|
||||
-- //10.0.1.254/Health -> /mnt/nas/Health
|
||||
-- //10.0.1.254/Home Movies -> /mnt/nas/Home Movies
|
||||
-- //10.0.1.254/Pictures -> /mnt/nas/Pictures
|
||||
--
|
||||
-- Keeping the share names verbatim is what reduces this to one uniform
|
||||
-- prefix substitution per format instead of eleven special cases. The same
|
||||
-- paths must be bind-mounted into the container at the same location, so the
|
||||
-- database and the container agree with no further translation.
|
||||
-- ============================================================================
|
||||
|
||||
PRAGMA foreign_keys = OFF;
|
||||
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 1. Drop the two vestigial library roots.
|
||||
--
|
||||
-- '\\korval\Audio Books' and '\\korval\Music Organized' are configured as
|
||||
-- library roots but contain ZERO files — all audio actually lives under
|
||||
-- \\korval\media\audiobooks and \\korval\media\music. Verified 2026-07-27:
|
||||
-- 0 files / 0 bytes under both.
|
||||
--
|
||||
-- The NOT EXISTS guard makes this a no-op if that ever stops being true, so
|
||||
-- this statement can never orphan a media_parts row.
|
||||
-- ---------------------------------------------------------------------------
|
||||
DELETE FROM section_locations
|
||||
WHERE root_path IN ('\\korval\Audio Books', '\\korval\Music Organized')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM media_parts mp
|
||||
WHERE mp.file LIKE section_locations.root_path || '\%'
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 2. Backslash / UNC form.
|
||||
--
|
||||
-- \\korval\media\movies\Film (2019)\Film.mkv
|
||||
-- -> /mnt/nas/media/movies/Film (2019)/Film.mkv
|
||||
--
|
||||
-- Order matters: swap the '\\korval\' prefix FIRST, then convert the
|
||||
-- remaining separators. Doing it the other way round destroys the prefix
|
||||
-- before it can be matched.
|
||||
--
|
||||
-- Spaces stay literal in this form — fstab needs \040 escaping, the database
|
||||
-- does not.
|
||||
-- ---------------------------------------------------------------------------
|
||||
UPDATE section_locations
|
||||
SET root_path = REPLACE(REPLACE(root_path, '\\korval\', '/mnt/nas/'), '\', '/')
|
||||
WHERE root_path LIKE '\\korval\%';
|
||||
|
||||
UPDATE media_parts
|
||||
SET file = REPLACE(REPLACE(file, '\\korval\', '/mnt/nas/'), '\', '/')
|
||||
WHERE file LIKE '\\korval\%';
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 3. file:// URL form.
|
||||
--
|
||||
-- file://korval/media/tvshows/Person%20of%20Interest/...
|
||||
-- -> file:///mnt/nas/media/tvshows/Person%20of%20Interest/...
|
||||
--
|
||||
-- Note the THIRD slash: 'file://korval/' is a host-qualified URL; a local
|
||||
-- path is 'file:///'. Separators are already forward slashes here, so no
|
||||
-- second REPLACE.
|
||||
--
|
||||
-- %20 IS LEFT ALONE ON PURPOSE. Plex URL-decodes these, so decoding them
|
||||
-- here would produce paths with literal '%20' in them and break every
|
||||
-- subtitle and stream reference that has a space in its name — which, given
|
||||
-- share names like "Radio Shows" and "Home Movies", is most of them.
|
||||
-- ---------------------------------------------------------------------------
|
||||
UPDATE media_streams
|
||||
SET url = REPLACE(url, 'file://korval/', 'file:///mnt/nas/')
|
||||
WHERE url LIKE 'file://korval/%';
|
||||
|
||||
UPDATE metadata_items
|
||||
SET guid = REPLACE(guid, 'file://korval/', 'file:///mnt/nas/')
|
||||
WHERE guid LIKE 'file://korval/%';
|
||||
|
||||
COMMIT;
|
||||
|
||||
PRAGMA foreign_keys = ON;
|
||||
|
||||
-- Reclaim the space freed by the rewrite and leave the file tidy for its
|
||||
-- first open by the new server. Safe, but slow on a 513 MB database — expect
|
||||
-- a minute or two.
|
||||
VACUUM;
|
||||
Reference in New Issue
Block a user