#!/bin/sh

# --- CONFIGURATION ---
SRC_DIR="/volume1/surveillance/@Snapshot"
DEST_DIR="/volume1/v1_web/webcam"
LOG_FILE="/volume1/v1_web/webcam/move_snapshots.log"

# --- EXECUTION ---
# Ensure destination folder exists
mkdir -p "$DEST_DIR"

# Verify source directory is accessible
if [ ! -d "$SRC_DIR" ]; then
    echo "$(date): Error - Source directory $SRC_DIR not found. Are you running as root?" >> "$LOG_FILE"
    exit 1
fi

# Find most recent and rename to latest.jpg
find "$SRC_DIR" -maxdepth 1 -name "*.jpg" -type f -printf '%T@ %p\0' | sort -znr | head -zn 1 | cut -zd ' ' -f2- | xargs -0 -I {} mv {} "${DEST_DIR}/latest.jpg"


# Find and move files, logging actions
echo "$(date): Starting snapshot transfer..." >> "$LOG_FILE"
find "$SRC_DIR" -name "*.jpg" -type f -exec mv -v {} "$DEST_DIR/" \; > "$LOG_FILE" 2>&1
echo "$(date): Transfer complete." >> "$LOG_FILE"
