#!/bin/bash

# Define your Jellyfin server URL and API key
JELLYFIN_URL="http://127.0.0.1:8096"
API_KEY="API KEY"

# Run journalctl command and search for the specified error messages
error_message_1="database disk image is malformed"
error_message_2="database or disk is full"

error_found_1=$(journalctl -u jellyfin --since "1 hour ago" | grep "$error_message_1")
error_found_2=$(journalctl -u jellyfin --since "1 hour ago" | grep "$error_message_2")

# If either error message is found, delete the database file and trigger library scan
if [ -n "$error_found_1" ] || [ -n "$error_found_2" ]; then
    echo "Error found in journal, deleting database file..."
    rm -f /var/lib/jellyfin/data/library.db
    # Optionally, replace with a backup and set correct permissions here.
    cp "/path/to/backups/Jellyfin/library.db" "/var/lib/jellyfin/data/library.db"
    /usr/bin/chown jellyfin:jellyfin "/var/lib/jellyfin/data/library.db"
    echo "Database file replaced with backup."

    # Trigger library scan
    echo "Triggering library scan..."
    curl -X POST \
        -H "Content-Type: application/json" \
        -H "X-Emby-Token: $API_KEY" \
        -d '{"Recursive":true}' \
        "$JELLYFIN_URL/library/refresh"
    echo "Library scan triggered."
    
    # Send Telegram message to admin
    curl -s -X POST -d "chat_id=CHAT ID" -d text="Jellyfin library.db had issues today. Check the logs!" https://api.telegram.org/botBOT:TOKEN/sendMessage
else
    echo "No error found in journal."
fi
exit 0