#!/usr/bin/env bash

# Storage monitor cron job
# Usage: configure cron to run every 5 minutes

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-storage-monitor.log"
LOCK_FILE="$LOG_DIR/storage_monitor.lock"

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

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

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