#!/bin/bash
# Enables EnableCrossLibrarySeriesMerging on all Jellyfin libraries.
# Usage: sudo bash enable-cross-library-merging.sh

JELLYFIN_ROOT="/var/lib/jellyfin/root/default"

if [ ! -d "$JELLYFIN_ROOT" ]; then
    echo "Jellyfin root not found at $JELLYFIN_ROOT"
    exit 1
fi

count=0
for opts in "$JELLYFIN_ROOT"/*/options.xml; do
    [ -f "$opts" ] || continue
    lib="$(basename "$(dirname "$opts")")"

    if grep -q '<EnableCrossLibrarySeriesMerging>true</EnableCrossLibrarySeriesMerging>' "$opts"; then
        echo "[$lib] already enabled"
    elif grep -q '<EnableCrossLibrarySeriesMerging>' "$opts"; then
        sed -i 's|<EnableCrossLibrarySeriesMerging>false</EnableCrossLibrarySeriesMerging>|<EnableCrossLibrarySeriesMerging>true</EnableCrossLibrarySeriesMerging>|' "$opts"
        echo "[$lib] updated false -> true"
        ((count++))
    else
        sed -i 's|</LibraryOptions>|  <EnableCrossLibrarySeriesMerging>true</EnableCrossLibrarySeriesMerging>\n</LibraryOptions>|' "$opts"
        echo "[$lib] inserted"
        ((count++))
    fi
done

echo ""
echo "Updated $count libraries. Restart Jellyfin and rescan libraries to regenerate keys."
echo "  sudo systemctl restart jellyfin"
