#!/usr/bin/env bash

# Archive dispatcher cron job
# Run nightly to move completed events to cold storage

set -euo pipefail

APP_DIR="$(cd "$(dirname "$0")/.." && pwd)"
cd "$APP_DIR"

LOG_DIR="$APP_DIR/storage/logs"
mkdir -p "$LOG_DIR"
LOG_FILE="$LOG_DIR/cron-archive-dispatcher.log"
LOCK_FILE="$LOG_DIR/archive_dispatcher.lock"

exec 200>"$LOCK_FILE"
if ! flock -n 200; then
    exit 0
fi

timestamp() {
    date --iso-8601=seconds
}

echo "[$(timestamp)] Starting storage:archive-pending" >> "$LOG_FILE"
if /usr/bin/env php artisan storage:archive-pending --no-interaction --quiet >> "$LOG_FILE" 2>&1; then
    echo "[$(timestamp)] storage:archive-pending completed" >> "$LOG_FILE"
else
    status=$?
    echo "[$(timestamp)] storage:archive-pending failed (exit $status)" >> "$LOG_FILE"
    exit $status
fi
