#!/usr/bin/env bash
#
# Background same-day sync, every 30 minutes.
#
#   ./jobs/sync-today.sh <shop-domain>
#
# Deliberately the PAGINATED poll, not a bulk operation: bulk runs one per shop and
# takes ~a minute, so a half-hourly bulk job would collide with the twice-daily one and
# with anyone tapping Sync. This covers whatever changed since the watermark, which
# between runs is minutes of trading.
#
# The twice-daily sync-recent.sh stays as-is. This does not replace it — that one walks
# a 14-day window and repairs late refunds and settled fees, which a same-day poll
# never sees.

set -uo pipefail

SHOP="${1:?usage: sync-today.sh <shop-domain>}"
APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PHP="${PHP_BIN:-/usr/bin/php}"
LOCK="/tmp/rpt-today-$(echo "$SHOP" | tr -c 'a-zA-Z0-9' '_').lock"

if [ -t 1 ]; then QUIET=""; else QUIET="--quiet"; fi

# Skip rather than queue: if the previous run is still going, the next one has nothing
# new to do anyway.
exec 9>"$LOCK"
if ! flock -n 9; then
  echo "$(date '+%F %T')  ${SHOP}: previous same-day sync still running, skipping"
  exit 0
fi

# No --recent and no --backfill: that is the incremental branch of sync-orders.php.
"$PHP" "$APP_DIR/jobs/sync-orders.php" --shop="$SHOP" $QUIET || exit 1
"$PHP" "$APP_DIR/jobs/aggregate.php" ${QUIET:+> /dev/null} || exit 1
"$PHP" "$APP_DIR/jobs/warm-cache.php" --shop="$SHOP" $QUIET || true
