#!/bin/bash
# =============================================================================
# AUTO SIGNAL CRON RUNNER
# =============================================================================
# Add ONE of these to crontab (crontab -e) for 30-second scheduling:
#
#   * * * * * /full/path/to/auto_signal_cron.sh >> /full/path/to/cron.log 2>&1
#   * * * * * sleep 30 && /full/path/to/auto_signal_cron.sh >> /full/path/to/cron.log 2>&1
#
# Edit BOT_PATH and PHP_BIN below before use.
# =============================================================================

BOT_PATH="/var/www/html/bot.php"   # ← set to your full bot.php path
PHP_BIN="/usr/bin/php"             # ← find yours: which php
LOCK_FILE="/tmp/auto_signal_cron.lock"
LOCK_TIMEOUT=55

if [ -f "$LOCK_FILE" ]; then
    LOCK_AGE=$(( $(date +%s) - $(stat -c %Y "$LOCK_FILE" 2>/dev/null || echo 0) ))
    if [ "$LOCK_AGE" -lt "$LOCK_TIMEOUT" ]; then
        echo "[$(date '+%Y-%m-%d %H:%M:%S')] Skipped: previous run still active (${LOCK_AGE}s)"
        exit 0
    fi
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Stale lock removed (${LOCK_AGE}s old)"
    rm -f "$LOCK_FILE"
fi

touch "$LOCK_FILE"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Scheduler triggered"
"$PHP_BIN" "$BOT_PATH" auto-signal-runner
EXIT_CODE=$?
rm -f "$LOCK_FILE"
[ $EXIT_CODE -ne 0 ] && echo "[$(date '+%Y-%m-%d %H:%M:%S')] ERROR: exit $EXIT_CODE"
exit $EXIT_CODE
