#!/usr/bin/env bash
#
# Scheduled re-sync: trailing window of orders, then aggregate, then settle fees.
#
#   ./jobs/sync-recent.sh <shop-domain> [days]
#
# Run from cron twice a day:
#   15 3,15 * * * /var/www/html/smartprinter-app/jobs/sync-recent.sh roycechocolate.myshopify.com 15 >> /var/log/rpt-sync.log 2>&1
#
# The three steps must run in this order and must not overlap:
#
#   1. sync-orders  writes facts and marks days dirty
#   2. aggregate    turns dirty days into rollups
#   3. sync-payments applies settled fees, re-marking those days
#   4. aggregate    folds the fees in
#   5. warm-cache   pre-generates the presets staff actually tap
#
# Aggregating before ingest finishes would roll up a day whose facts are not all in
# yet and then clear the flag, leaving a confidently wrong number until something else
# happens to touch that day.
#
# Step 3 re-marks days dirty, so a second aggregate pass runs at the end to fold the
# fees in rather than waiting for the next cycle.

set -uo pipefail

SHOP="${1:?usage: sync-recent.sh <shop-domain> [days]}"
DAYS="${2:-15}"

# Quiet under cron, verbose when a human runs it. A silent 15-minute foreground run is
# indistinguishable from a hung one, which is exactly when you need the progress.
if [ -t 1 ]; then QUIET=""; else QUIET="--quiet"; fi

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

# Shopify allows one bulk query per shop at a time, and a slow run must not have the
# next schedule stack on top of it. -n: skip this cycle rather than queue behind it.
exec 9>"$LOCK"
if ! flock -n 9; then
  echo "$(date '+%F %T')  ${SHOP}: previous run still going, skipping this cycle"
  exit 0
fi

echo "$(date '+%F %T')  ${SHOP}: starting ${DAYS}-day re-sync"

run() {
  local label="$1"; shift
  if ! "$@"; then
    echo "$(date '+%F %T')  ${SHOP}: ${label} FAILED (exit $?)"
    return 1
  fi
}

# A failure in any step stops the chain: aggregating on top of a half-finished ingest
# is worse than being stale until the next cycle.
run "sync-orders"   "$PHP" "$APP_DIR/jobs/sync-orders.php"   --shop="$SHOP" --recent="$DAYS" $QUIET || exit 1
run "aggregate"     "$PHP" "$APP_DIR/jobs/aggregate.php"                                             || exit 1
run "sync-payments" "$PHP" "$APP_DIR/jobs/sync-payments.php" --shop="$SHOP" $QUIET                  || exit 1
# Fees re-marked their days; fold them in now instead of next cycle.
run "aggregate"     "$PHP" "$APP_DIR/jobs/aggregate.php"                                             || exit 1

# Warm the presets LAST: the aggregate above bumped rollup_version, so anything warmed
# earlier in this run would already be invalid.
run "warm-cache"    "$PHP" "$APP_DIR/jobs/warm-cache.php" --shop="$SHOP" $QUIET                      || true

echo "$(date '+%F %T')  ${SHOP}: done"
