#!/usr/bin/env bash set -euo pipefail # Cron helper for refreshing station catalog and rebuilding assets. # Optional env vars: # - REPO_DIR: repository root (defaults to script parent) # - LOCK_FILE: lock path (defaults to /tmp/radioplayer-refresh-stations.lock) # - LOG_FILE: log path (defaults to /tmp/radioplayer-refresh-stations.log) # - LOG_MAX_BYTES: rotate log when it grows beyond this size (default 1048576) # - LOG_KEEP_COUNT: number of rotated logs to keep (default 5) # - DEPLOY_CMD: optional shell command executed after successful build REPO_DIR="${REPO_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}" LOCK_FILE="${LOCK_FILE:-/tmp/radioplayer-refresh-stations.lock}" LOG_FILE="${LOG_FILE:-/tmp/radioplayer-refresh-stations.log}" LOG_MAX_BYTES="${LOG_MAX_BYTES:-1048576}" LOG_KEEP_COUNT="${LOG_KEEP_COUNT:-5}" rotate_log_if_needed() { if [[ ! -f "$LOG_FILE" ]]; then return fi local size size=$(wc -c < "$LOG_FILE") if [[ "$size" -lt "$LOG_MAX_BYTES" ]]; then return fi local i for ((i=LOG_KEEP_COUNT; i>=1; i--)); do if [[ -f "$LOG_FILE.$i" ]]; then if [[ "$i" -ge "$LOG_KEEP_COUNT" ]]; then rm -f "$LOG_FILE.$i" else mv "$LOG_FILE.$i" "$LOG_FILE.$((i + 1))" fi fi done mv "$LOG_FILE" "$LOG_FILE.1" } mkdir -p "$(dirname "$LOCK_FILE")" "$(dirname "$LOG_FILE")" rotate_log_if_needed exec 9>"$LOCK_FILE" if ! flock -n 9; then echo "[$(date -Is)] refresh skipped: another run is active" >> "$LOG_FILE" exit 0 fi { echo "[$(date -Is)] refresh start" cd "$REPO_DIR" npm ci --silent npm run update:stations npm run build if [[ -n "${DEPLOY_CMD:-}" ]]; then echo "[$(date -Is)] running deploy command" bash -lc "$DEPLOY_CMD" fi echo "[$(date -Is)] refresh complete" } >> "$LOG_FILE" 2>&1