#!/usr/bin/env bash

# Laravel scheduler runner
# Add to crontab: * * * * * /path/to/repo/cron/scheduler.sh

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

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

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

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