#!/usr/bin/env bash
set -euo pipefail

# Cron helper for refreshing only the managed station catalog.
# Optional env vars:
# - REPO_DIR: repository root (defaults to script parent)
# - LOCK_FILE: lock path (defaults to /tmp/radioplayer-update-stations.lock)
# - LOG_FILE: log path (defaults to /tmp/radioplayer-update-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)
# - POST_UPDATE_CMD: optional shell command executed after successful station update

REPO_DIR="${REPO_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
LOCK_FILE="${LOCK_FILE:-/tmp/radioplayer-update-stations.lock}"
LOG_FILE="${LOG_FILE:-/tmp/radioplayer-update-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)] update skipped: another run is active" >> "$LOG_FILE"
  exit 0
fi

{
  echo "[$(date -Is)] update start"
  cd "$REPO_DIR"
  npm ci --silent
  npm run update:stations

  if [[ -n "${POST_UPDATE_CMD:-}" ]]; then
    echo "[$(date -Is)] running post-update command"
    bash -lc "$POST_UPDATE_CMD"
  fi

  echo "[$(date -Is)] update complete"
} >> "$LOG_FILE" 2>&1
