#!/etc/profiles/per-user/jawz/bin/bash

KEEP_DIR="/srv/pool/scrapping/JawZ/keep"
SOURCE_DIR="/srv/pool/scrapping/JawZ/gallery-dl"

shopt -s globstar nullglob

cd "$KEEP_DIR" || exit 1

for keep_path in **/; do
    relative_path="${keep_path%/}"
    src_path="$SOURCE_DIR/$relative_path"
    dest_path="$KEEP_DIR/$relative_path"

    if [ ! -d "$src_path" ]; then
        continue
    fi

    echo "Processing: $relative_path"
    mkdir -p "$dest_path"

    for src_file in "$src_path"/*; do
        filename="$(basename "$src_file")"
        dest_file="$dest_path/$filename"

        if [ ! -f "$src_file" ]; then
            continue
        fi

        if [ ! -f "$dest_file" ]; then
            mv "$src_file" "$dest_file"
            echo "→ Moved: $filename"
            continue
        fi

        if cmp -s "$src_file" "$dest_file"; then
            echo "✓ Duplicate: $filename — deleting source"
            rm "$src_file"
            continue
        fi

        echo "⚠ Conflict (not identical): $filename"
    done
done

fd . "$SOURCE_DIR" -td -te -x rmdir {} \;
