#!/bin/bash

set -e

# Configuration
CONTAINER_NAME="jellyfin"
DB_PATH_IN_CONTAINER="/config/data"
DB_FILES=("library.db" "jellyfin.db")
BACKUP_DIR="/tmp/jellyfin_db_backup_$(date +%Y%m%d_%H%M%S)"
REPAIR_DIR="/tmp/jellyfin_db_repair"

# --- Functions ---

# Function to print messages
log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}

# Function to stop the Jellyfin container
stop_container() {
    log "Stopping Jellyfin container..."
    docker stop "$CONTAINER_NAME"
}

# Function to start the Jellyfin container
start_container() {
    log "Starting Jellyfin container..."
    docker start "$CONTAINER_NAME"
}

# Function to create a backup of the database files
backup_database() {
    log "Backing up database files to $BACKUP_DIR..."
    mkdir -p "$BACKUP_DIR"
    for db_file in "${DB_FILES[@]}"; do
        docker cp "${CONTAINER_NAME}:${DB_PATH_IN_CONTAINER}/${db_file}" "$BACKUP_DIR/"
    done
}

# Function to repair a database file
repair_database() {
    local db_file="$1"
    local db_path_in_repair_dir="${REPAIR_DIR}/${db_file}"
    local sql_dump_file="${REPAIR_DIR}/${db_file}.sql"
    local new_db_file="${REPAIR_DIR}/${db_file}.new"

    log "Repairing ${db_file}..."

    # Check for corruption
    log "Running integrity check on ${db_file}..."
    if sqlite3 "$db_path_in_repair_dir" "PRAGMA integrity_check;" | grep -q "ok"; then
        log "${db_file} is not corrupted. Skipping repair."
        return
    fi

    log "Dumping ${db_file} to SQL file..."
    sqlite3 "$db_path_in_repair_dir" .dump > "$sql_dump_file"

    log "Creating new database from SQL dump..."
    sqlite3 "$new_db_file" < "$sql_dump_file"

    log "Replacing old database with the new one..."
    mv "$new_db_file" "$db_path_in_repair_dir"
}

# --- Main Script ---

# Stop the container
stop_container

# Create repair directory
mkdir -p "$REPAIR_DIR"

# Copy database files to repair directory
log "Copying database files to repair directory..."
for db_file in "${DB_FILES[@]}"; do
    docker cp "${CONTAINER_NAME}:${DB_PATH_IN_CONTAINER}/${db_file}" "$REPAIR_DIR/"
done

# Repair each database file
for db_file in "${DB_FILES[@]}"; do
    repair_database "$db_file"
done

# Copy repaired files back to the container
log "Copying repaired files back to the container..."
for db_file in "${DB_FILES[@]}"; do
    docker cp "${REPAIR_DIR}/${db_file}" "${CONTAINER_NAME}:${DB_PATH_IN_CONTAINER}/${db_file}"
done

# Clean up repair directory
rm -rf "$REPAIR_DIR"

# Start the container
start_container

log "Database repair process completed."
