cat > /var/www/watermarked_optimized/upscale_ebay.sh << 'ENDOFSCRIPT'
#!/bin/bash

CSV="/var/www/watermarked_optimized/oakbooks_books_with_small_images.csv"
IMG_DIR="/var/www/images_watermarked"
LOG="/var/www/watermarked_optimized/upscale_log.txt"
PROGRESS="/var/www/watermarked_optimized/upscale_progress.txt"
TARGET=800

echo "Starting eBay upscale job at $(date)" | tee "$LOG"
echo "CSV: $CSV" | tee -a "$LOG"
echo "Image dir: $IMG_DIR" | tee -a "$LOG"
echo "---" | tee -a "$LOG"

count=0
skipped=0
upscaled=0
missing=0
errors=0
total=$(tail -n +2 "$CSV" | wc -l)

tail -n +2 "$CSV" | cut -d',' -f8 | while IFS= read -r filename; do
    filename=$(echo "$filename" | tr -d '\r' | xargs)
    count=$((count + 1))

    if [ -z "$filename" ]; then
        echo "[$count/$total] SKIP: empty filename" | tee -a "$LOG"
        continue
    fi

    filepath="$IMG_DIR/$filename"

    if [ ! -f "$filepath" ]; then
        echo "[$count/$total] MISSING: $filename" | tee -a "$LOG"
        missing=$((missing + 1))
        continue
    fi

    dims=$(identify -format "%w %h" "$filepath" 2>/dev/null)
    if [ -z "$dims" ]; then
        echo "[$count/$total] ERROR reading: $filename" | tee -a "$LOG"
        errors=$((errors + 1))
        continue
    fi

    width=$(echo $dims | cut -d' ' -f1)
    height=$(echo $dims | cut -d' ' -f2)

    if [ "$width" -ge "$height" ]; then
        longest=$width
    else
        longest=$height
    fi

    if [ "$longest" -ge "$TARGET" ]; then
        skipped=$((skipped + 1))
        if [ $((skipped % 100)) -eq 0 ]; then
            echo "[$count/$total] OK (${width}x${height}): $filename" | tee -a "$LOG"
        fi
    else
        if mogrify -resize "${TARGET}x${TARGET}>" "$filepath" 2>>/var/www/watermarked_optimized/errors.txt; then
            upscaled=$((upscaled + 1))
            echo "[$count/$total] UPSCALED (${width}x${height} -> ${TARGET}px longest): $filename" | tee -a "$LOG"
        else
            echo "[$count/$total] ERROR upscaling: $filename" | tee -a "$LOG"
            errors=$((errors + 1))
        fi
    fi

    if [ $((count % 100)) -eq 0 ]; then
        echo "Progress: $count/$total | Upscaled: $upscaled | Skipped: $skipped | Missing: $missing | Errors: $errors" | tee "$PROGRESS"
    fi

done

echo "---" | tee -a "$LOG"
echo "Done at $(date)" | tee -a "$LOG"
echo "Total processed: $count" | tee -a "$LOG"
echo "Upscaled: $upscaled" | tee -a "$LOG"
echo "Already OK (skipped): $skipped" | tee -a "$LOG"
echo "Missing files: $missing" | tee -a "$LOG"
echo "Errors: $errors" | tee -a "$LOG"
ENDOFSCRIPT
chmod +x /var/www/watermarked_optimized/upscale_ebay.sh && echo "Script created OK" && ls -lh /var/www/watermarked_optimized/upscale_ebay.sh
