#!/bin/sh
# ============================================================
# log_flush.sh -- Async ring-buffer to USB flush daemon
#
# Runs in the background, calling sync() on the log directory
# every 5 seconds so boot logs survive even on a hard reset.
# Writes a periodic heartbeat so agents can detect hung sessions.
# Exits cleanly when the /tmp/hiperiso_done sentinel appears,
# writing a final flush marker.
#
# Usage:  log_flush.sh <log_dir>
# ============================================================

LOG_DIR="${1:-}"
INTERVAL=5
SENTINEL="/tmp/hiperiso_done"
HEARTBEAT_INTERVAL=12

if [ -z "$LOG_DIR" ]; then
    printf '[log_flush] FATAL: no log directory specified\n'
    printf '[log_flush] usage: log_flush.sh <log_dir>\n'
    exit 1
fi

if [ ! -d "$LOG_DIR" ]; then
    printf '[log_flush] FATAL: log directory does not exist: %s\n' "$LOG_DIR"
    exit 1
fi

printf '[log_flush] Started -- syncing %s every %ds\n' "$LOG_DIR" "$INTERVAL"

_flush_count=0

while true; do
    # ── Check sentinel: exit gracefully ──────────────────────
    if [ -f "$SENTINEL" ]; then
        printf '[log_flush] Sentinel detected, performing final sync...\n'
        sync
        printf '[log_flush] Exiting after %d sync cycles\n' "$_flush_count"
        exit 0
    fi

    # ── Check if log directory still accessible ──────────────
    # (USB might have been unplugged)
    if [ ! -d "$LOG_DIR" ]; then
        printf '[log_flush] WARNING: log dir vanished (USB unplugged?) -- waiting for sentinel\n'
        sleep "$INTERVAL"
        continue
    fi

    # ── Flush dirty pages to the USB device ──────────────────
    sync 2>/dev/null

    _flush_count=$(( _flush_count + 1 ))

    # ── Write periodic heartbeat ─────────────────────────────
    if [ $(( _flush_count % HEARTBEAT_INTERVAL )) -eq 0 ]; then
        _up=$(cut -d' ' -f1 /proc/uptime 2>/dev/null)
        printf 'cycle=%d uptime=%s\n' "$_flush_count" "${_up:-0}" \
            > "${LOG_DIR}/HEARTBEAT" 2>/dev/null
        printf '[log_flush] cycle %d (%d min) -- OK\n' \
            "$_flush_count" "$(( _flush_count / HEARTBEAT_INTERVAL ))"
    fi

    sleep "$INTERVAL"
done
