#!/bin/sh
# Kindle screensaver pull script — installed to /mnt/us/linkss/screensavers/run.sh
# Runs on each screensaver trigger to fetch the latest image from the server.

SERVER="http://192.168.1.118:18888"
SCREENSAVER_DIR="/mnt/us/linkss/screensavers"
OUTPUT_FILE="$SCREENSAVER_DIR/bg_ss00.png"
LOG="$SCREENSAVER_DIR/pull.log"

# Rotate log if it gets too big (keep last 4KB)
if [ -f "$LOG" ]; then
    LOGSIZE=$(wc -c < "$LOG" 2>/dev/null)
    if [ "$LOGSIZE" -gt 4096 ] 2>/dev/null; then
        tail -c 2048 "$LOG" > "$LOG.tmp"
        mv "$LOG.tmp" "$LOG"
    fi
fi

echo "$(date): Script triggered" >> "$LOG"

# Ensure output directory exists
mkdir -p "$SCREENSAVER_DIR"

# Wait for Wi-Fi (up to 30 seconds, check every 5)
ATTEMPTS=0
MAX_ATTEMPTS=6
while [ $ATTEMPTS -lt $MAX_ATTEMPTS ]; do
    # Check for network connectivity — ping the server or check WLAN interface
    if wget -q --spider "$SERVER/latest.png" 2>/dev/null; then
        echo "$(date): Network ready after ${ATTEMPTS}x5s wait" >> "$LOG"
        break
    fi
    ATTEMPTS=$((ATTEMPTS + 1))
    echo "$(date): Waiting for network ($ATTEMPTS/$MAX_ATTEMPTS)..." >> "$LOG"
    sleep 5
done

# Download the latest screensaver
if wget -q -O "$OUTPUT_FILE" "$SERVER/latest.png" 2>>"$LOG"; then
    SIZE=$(wc -c < "$OUTPUT_FILE" 2>/dev/null)
    echo "$(date): Downloaded ${SIZE} bytes" >> "$LOG"
else
    echo "$(date): FAILED to download from $SERVER/latest.png" >> "$LOG"
    # Try to restore last good image if download fails
    if [ -f "$SCREENSAVER_DIR/bg_ss00.png.bak" ]; then
        cp "$SCREENSAVER_DIR/bg_ss00.png.bak" "$OUTPUT_FILE"
        echo "$(date): Restored backup image" >> "$LOG"
    fi
fi