#!/bin/bash

# Extract existing Synology thumbnails from @eaDir into eaDir_tmp so thumbgen skips regeneration
# Usage: ./extract_eadir_to_tmp.sh /volume1/YourShare/path

set -uo pipefail

if [ $# -eq 0 ]; then
    echo "Usage: $0 <directory_path>"
    exit 1
fi

TARGET_DIR="$1"

if [ ! -d "$TARGET_DIR" ]; then
    echo "Error: '$TARGET_DIR' is not a directory"
    exit 1
fi

echo "=== Extracting @eaDir thumbnails to eaDir_tmp ==="
echo "Target: $TARGET_DIR"

# Only TARGET_DIR/@eaDir (not nested .../@eaDir/.../@eaDir from bad prior runs; those hit chmod 555 parents)
find "$TARGET_DIR" -mindepth 1 -maxdepth 1 -type d -name '@eaDir' -print0 | while IFS= read -r -d '' EADIR; do
    PARENT_DIR="$(dirname "$EADIR")"

    # Each immediate subdir under @eaDir corresponds to a source filename
    find "$EADIR" -mindepth 1 -maxdepth 1 -type d -print0 | while IFS= read -r -d '' ENTRY; do
        BASENAME="$(basename "$ENTRY")"
        DEST_DIR="$PARENT_DIR/eaDir_tmp/$BASENAME"

        mkdir -p "$DEST_DIR" || continue

        # Copy without overwriting existing files in eaDir_tmp
        for F in \
            SYNOVIDEO_VIDEO_SCREENSHOT.jpg \
            SYNOPHOTO_THUMB_XL.jpg \
            SYNOPHOTO_THUMB_B.jpg \
            SYNOPHOTO_THUMB_M.jpg \
            SYNOPHOTO_THUMB_PREVIEW.jpg \
            SYNOPHOTO_THUMB_S.jpg; do
            if [ -f "$ENTRY/$F" ] && [ ! -f "$DEST_DIR/$F" ]; then
                cp "$ENTRY/$F" "$DEST_DIR/$F"
            fi
        done
    done
done

echo "=== Done. Existing thumbnails copied into eaDir_tmp where available. ==="

