#!/bin/sh
# Sync Kobo highlights to home server with FBInk notifications
# Place at: /usr/local/bin/sync_highlights.sh

DB="/mnt/onboard/.kobo/KoboReader.sqlite"
ENDPOINT="http://192.168.88.69:42070/api/highlights"
LOGFILE="/mnt/onboard/.adds/kb_exfiltrator.log"

# Create log directory if needed
mkdir -p /mnt/onboard/.adds

# Check if FBInk is available
FBINK=""
if command -v fbink >/dev/null 2>&1; then
    FBINK="fbink"
elif [ -x /usr/local/bin/fbink ]; then
    FBINK="/usr/local/bin/fbink"
elif [ -x /usr/bin/fbink ]; then
    FBINK="/usr/bin/fbink"
fi

# Show "Syncing..." message
if [ -n "$FBINK" ]; then
    $FBINK -q -pm -y 10 "Syncing highlights..."
fi

# Log with timestamp
echo "=== $(date) ===" >> "$LOGFILE"

# Run exfiltrator and capture output
OUTPUT=$(/usr/local/bin/kb_exfiltrator "$DB" "$ENDPOINT" 2>&1)
EXIT_CODE=$?

# Log the output
echo "$OUTPUT" >> "$LOGFILE"

# Parse the output for stats (if successful)
if [ $EXIT_CODE -eq 0 ]; then
    # Try to extract highlight count from output
    COUNT=$(echo "$OUTPUT" | grep -o 'Extracted [0-9]* highlights' | grep -o '[0-9]*')

    if [ -n "$FBINK" ]; then
        if [ -n "$COUNT" ]; then
            $FBINK -q -pm -y 10 "✓ Synced $COUNT highlights!"
        else
            $FBINK -q -pm -y 10 "✓ Highlights synced!"
        fi
    fi

    echo "Success: Highlights synced!" >> "$LOGFILE"

    # Clear notification after 2 seconds
    sleep 2
    if [ -n "$FBINK" ]; then
        $FBINK -q -s
    fi

    exit 0
else
    # Failure
    if [ -n "$FBINK" ]; then
        $FBINK -q -pm -y 10 "✗ Sync failed! Check log"
    fi

    echo "Error: Sync failed" >> "$LOGFILE"

    # Clear notification after 3 seconds
    sleep 3
    if [ -n "$FBINK" ]; then
        $FBINK -q -s
    fi

    exit 1
fi
