#!/bin/bash
# epctofcam-spi_flash-sync
# Copies the contents of /mnt/spi_flash into /usr/local/share/epctofcam/
# at every boot, triggered by the epctofcam-spi_flash-sync.service unit.
#
# The SPI NOR flash is mounted via a JFFS2 automount unit; accessing
# the mount-point path below causes systemd to trigger that mount
# automatically before this script reads any files.

set -euo pipefail

SRC="/mnt/spi_flash/"
DST="/usr/local/share/epctofcam/"
LOG_TAG="epctofcam-spi_flash-sync"

log()  { logger -t "$LOG_TAG" -- "$*"; echo "$*"; }
die()  { log "ERROR: $*"; exit 1; }

# ── Sanity checks ────────────────────────────────────────────────────────────

# Verify the source is actually a mounted filesystem, not an empty directory.
if ! mountpoint -q "$SRC"; then
    die "$SRC is not a mountpoint - aborting to avoid wiping destination."
fi

# ── Create destination if missing ────────────────────────────────────────────
if [ ! -d "$DST" ]; then
    log "Destination $DST does not exist, creating it."
    mkdir -p "$DST"
fi

# ── Sync ─────────────────────────────────────────────────────────────────────
log "Starting sync: $SRC -> $DST"

if command -v rsync &>/dev/null; then
    # Preferred: rsync mirrors the source exactly (--delete removes stale files)
    rsync -a --delete --no-owner --no-group "$SRC" "$DST"
else
    # Fallback: plain cp when rsync is not installed
    log "rsync not found, falling back to cp."
    rm -rf "${DST:?}"/*
    cp -a "$SRC/." "$DST"
fi

log "Sync complete."