#!/bin/bash

# Schedule Parser Bot - Setup Cron Jobs

SCRIPT_PATH="/var/www/html/tgbot/scheduleparser/run.php"
LOG_PATH="/var/log/schedule_checker.log"

echo "⚙️  Schedule Parser Bot - Cron Setup"
echo "===================================="
echo ""

# Check if script exists
if [ ! -f "$SCRIPT_PATH" ]; then
    echo "❌ Script not found at: $SCRIPT_PATH"
    exit 1
fi

echo "📍 Script path: $SCRIPT_PATH"
echo "📍 Log path: $LOG_PATH"
echo ""

# Create log file if it doesn't exist
if [ ! -f "$LOG_PATH" ]; then
    echo "📝 Creating log file..."
    touch "$LOG_PATH"
    chmod 666 "$LOG_PATH"
fi

echo "🔍 Choose user to run cron jobs:"
echo "1) Current user ($(whoami))"
echo "2) www-data (web server user)"
echo "3) root"
echo ""
read -p "Enter choice (1-3): " user_choice

case $user_choice in
    1)
        CRON_USER=$(whoami)
        CRONTAB_CMD="crontab -e"
        ;;
    2)
        CRON_USER="www-data"
        CRONTAB_CMD="sudo crontab -e -u www-data"
        ;;
    3)
        CRON_USER="root"
        CRONTAB_CMD="sudo crontab -e"
        ;;
    *)
        echo "❌ Invalid choice"
        exit 1
        ;;
esac

echo ""
echo "📋 Cron jobs to add for user: $CRON_USER"
echo ""
echo "Job 1 - 08:00 (8 AM):"
echo "0 8 * * * php $SCRIPT_PATH >> $LOG_PATH 2>&1"
echo ""
echo "Job 2 - 18:00 (6 PM):"
echo "0 18 * * * php $SCRIPT_PATH >> $LOG_PATH 2>&1"
echo ""

read -p "Continue with crontab setup? (y/n): " confirm

if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
    echo ""
    echo "Opening crontab editor..."
    echo "👉 Add the lines above to crontab, then save and exit"
    echo ""
    eval $CRONTAB_CMD
else
    echo "❌ Cancelled"
    exit 1
fi
