ba-auto-daily/ba_cron_run.sh

61 lines
2.7 KiB
Bash
Executable File

#!/usr/bin/env bash
# Cron entry point for ba_dailies.sh presets. Pure process-locking/logging
# plumbing -- no game-automation logic, same "thin wrapper" spirit as
# ba_dailies.sh itself (see CLAUDE.md's Bash policy).
#
# The shared flock lock exists because "daily" fires twice a day (3:30 and
# 4:30) and "q4h" fires every 4 hours -- without a lock, two overlapping
# invocations would both drive xdotool/scrot against the same game window
# at once, which is unsafe. -n (non-blocking): if a previous run is still
# in progress, this invocation is skipped entirely rather than queued, so
# a scheduled fire time can never silently run late.
#
# Logs to ~/ba_logs/<preset>.log -- one file per preset, so "daily" and
# "q4h" never interleave. Every line is one of four explicitly-tagged
# outcomes (OK / FAILED / SKIPPED -- previous run still in progress /
# SKIPPED -- paused) specifically so a real failure can be found with a
# single command, e.g.:
# grep -E 'FAILED|SKIPPED' ~/ba_logs/*.log
# A bare exit code alone can't do this: flock and a genuinely crashed task
# both exit 1, so lock acquisition is checked as its own explicit step
# (via an fd-based flock, not the "flock -n LOCKFILE COMMAND" form used
# originally) rather than folded into the wrapped command's own exit code.
# Likewise, ba_daily.py's manual pause switch (config.PAUSE_FLAG_PATH,
# toggled via `./ba_dailies.sh pause`/`resume`) exits with the distinct
# PAUSE_EXIT_CODE (75) below rather than the generic failure code, so a
# deliberate pause never gets logged as a crash.
set -uo pipefail
# Resolves its own directory (same pattern ba_dailies.sh itself already
# uses) rather than assuming a fixed ~/ba_dailies.sh copy -- the runtime
# now runs directly out of this git checkout, so cron's own crontab entry
# points straight at this file's real path (see CLAUDE.md's "Deployment
# model") and this always calls the ba_dailies.sh sitting right next to it,
# wherever the checkout lives.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PRESET="${1:?usage: ba_cron_run.sh <preset>}"
LOG_DIR="$HOME/ba_logs"
LOG_FILE="$LOG_DIR/$PRESET.log"
LOCK_FILE="$LOG_DIR/ba_dailies.lock"
mkdir -p "$LOG_DIR"
{
exec 9>"$LOCK_FILE"
if ! flock -n 9; then
echo "=== $(date -Iseconds) SKIPPED $PRESET -- previous run still in progress ==="
exit 0
fi
echo "=== $(date -Iseconds) starting $PRESET ==="
"$SCRIPT_DIR/ba_dailies.sh" "$PRESET"
status=$?
if [ "$status" -eq 0 ]; then
echo "=== $(date -Iseconds) finished $PRESET OK (exit 0) ==="
elif [ "$status" -eq 75 ]; then
echo "=== $(date -Iseconds) SKIPPED $PRESET -- paused ==="
else
echo "=== $(date -Iseconds) finished $PRESET FAILED (exit $status) ==="
fi
} >> "$LOG_FILE" 2>&1