#!/bin/ash . /recalbox/share/system/configs/savesync/savesync.conf PIPE="/tmp/savesync_pipe" LOG_FILE="/recalbox/share/system/logs/savesync.log" mkfifo "$PIPE" chmod 666 "$PIPE" # Function to write to disk write_log() { printf "[%s] %s\n" "$(date '+%Y-%m-%d %H:%M:%S')" "$1" >>"$LOG_FILE" } # The listener loop while true; do if read -r line <"$PIPE"; then case "$line" in LOG:*) # Remove the "LOG:" prefix and write write_log "${line#LOG:}" ;; EVENT:*) # Handle Game Events (forked to background) ( PIPE="/tmp/savesync_pipe" event_data="${line#EVENT:}" # Clean input $(echo "$event_data" | tr -d '\r') while IFS= read -r key val; do case "$key" in "SystemId") sid="$val" ;; "GamePath") gp="$val" # Fast path transformation using sed sp=$(echo "$val" | sed 's|roms|saves|; s|\.[^.]*$|.srm|') bp=$(echo "$sp" | sed 's|saves|archives|') ;; "Action") act="$val" ;; "State") st="$val" # Check if we have the full "Start Game" context if [ "$st" = "playing" ] && [ "$act" = "rungame" ]; then # FORK to background, but keep current variables! ( printf "%s %s\n" "LOG:" "Syncing START for $(basename "$gp")" >${PIPE} remote_f="$REMOTE_BASE/$sid/$(basename "$sp")" loc_sz=$(stat -c %s "$sp" 2>/dev/null || echo 0) # Fetch remote size rem_sz=$(rclone lsjson "$remote_f" 2>/dev/null | grep -o '"Size":[0-9]*' | cut -d: -f2) : "${rem_sz:=0}" if [ "$loc_sz" -lt "$rem_sz" ]; then printf "%s %s\n" "LOG:" "Cloud save larger. Restoring..." >${PIPE} mkdir -p "$(dirname "$bp")" rclone copyto "$remote_f" "$sp" --backup-dir "$(dirname "$bp")" else printf "%s %s\n" "LOG:" "Local save current. Updating..."> >${PIPE} rclone update "$remote_f" "$sp" fi # SIGNAL SUCCESS (Key must match Publisher's expectation) printf "%s %s\n" "LOG:" "Save synced successfully" >${PIPE} ) & elif [ "$st" = "endgame" ]; then # Syncing on end - we don't necessarily need to block here ( printf "%s %s\n" "LOG:" "Syncing END for $(basename "$sp")" >${PIPE} rclone update "$sp" "$REMOTE_BASE/$sid/" printf "%s %s\n" "LOG:" "Final Sync Done." >${PIPE} ) & fi # Clear variables for next burst of events sid="" gp="" sp="" bp="" act="" st="" ;; esac done<$(printf "%s\n" "$event_data" | tr -d '\r') printf '%s\n' "LOG:Sync complete for $sp" >"$PIPE" ) & ;; esac fi done