#!/bin/bash

# Calibre Library Backup Script
# This script backs up the Calibre Library to a network share

set -e

# Configuration
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
SOURCE_DIR="/home/acedanger/Calibre Library/"
DEST_DIR="/mnt/share/media/books/"
LOG_DIR="$SCRIPT_DIR/logs"
LOG_FILE="$LOG_DIR/calibre-backup.log"

# Ensure log directory exists
mkdir -p "$LOG_DIR"

# Function to log messages with timestamp
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

# Check if source directory exists
if [ ! -d "$SOURCE_DIR" ]; then
    log_message "ERROR: Source directory does not exist: $SOURCE_DIR"
    exit 1
fi

# Check if destination directory is accessible
if [ ! -d "$DEST_DIR" ]; then
    log_message "ERROR: Destination directory not accessible: $DEST_DIR"
    log_message "Make sure the network share is mounted"
    exit 1
fi

# Start backup
log_message "Starting Calibre Library backup..."
log_message "Source: $SOURCE_DIR"
log_message "Destination: $DEST_DIR"

# Perform the backup using rsync
# Use a temp file to capture output while preserving rsync's exit code
RSYNC_TMP=$(mktemp)
if rsync -rtvp --delete --exclude="*.tmp" "$SOURCE_DIR" "$DEST_DIR" > "$RSYNC_TMP" 2>&1; then
    cat "$RSYNC_TMP" | tee -a "$LOG_FILE"
    log_message "Backup completed successfully"
    rm -f "$RSYNC_TMP"
    exit 0
else
    RSYNC_EXIT=$?
    cat "$RSYNC_TMP" | tee -a "$LOG_FILE"
    log_message "ERROR: Backup failed with exit code $RSYNC_EXIT"
    rm -f "$RSYNC_TMP"
    exit $RSYNC_EXIT
fi