#!/bin/bash
# -*- coding: utf-8 -*-

# Script to run Telegram Bot with auto-restart (forever)
# Usage: ./start-forever.sh

export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8

cd "$(dirname "$0")"

PID_FILE="bot.pid"
LOG_FILE="bot.log"
FOREVER_PID_FILE="bot.forever.pid"
MAX_RESTARTS=10
RESTART_DELAY=5

# تابع برای kill کردن همه process های ربات
kill_all_bot_processes() {
    PIDS=$(ps aux | grep -E "[p]hp.*public/index\.php" | awk '{print $2}')
    if [ -n "$PIDS" ]; then
        for PID in $PIDS; do
            kill "$PID" 2>/dev/null
        done
        sleep 2
        REMAINING=$(ps aux | grep -E "[p]hp.*public/index\.php" | awk '{print $2}')
        if [ -n "$REMAINING" ]; then
            for PID in $REMAINING; do
                kill -9 "$PID" 2>/dev/null
            done
        fi
    fi
    rm -f "$PID_FILE"
}

# بررسی اینکه آیا forever script در حال اجراست
if [ -f "$FOREVER_PID_FILE" ]; then
    FOREVER_PID=$(cat "$FOREVER_PID_FILE")
    if ps -p "$FOREVER_PID" > /dev/null 2>&1; then
        echo "⚠️  Forever script is already running (PID: $FOREVER_PID)"
        echo "To stop, use: kill $FOREVER_PID"
        exit 1
    else
        rm -f "$FOREVER_PID_FILE"
    fi
fi

# بررسی اینکه آیا bot در حال اجراست
if [ -f "$PID_FILE" ]; then
    OLD_PID=$(cat "$PID_FILE")
    if ps -p "$OLD_PID" > /dev/null 2>&1; then
        echo "⚠️  Bot is already running (PID: $OLD_PID)"
        echo "Stopping old instance..."
        kill_all_bot_processes
        sleep 2
    else
        rm -f "$PID_FILE"
    fi
fi

echo "🚀 Starting bot with auto-restart (forever mode)..."
echo "This script will automatically restart the bot if it crashes."
echo "Press Ctrl+C to stop."
echo ""

# اجرای forever loop در background
(
    RESTART_COUNT=0
    
    while true; do
        # بررسی تعداد restart ها
        if [ $RESTART_COUNT -ge $MAX_RESTARTS ]; then
            echo "[$(date '+%Y-%m-%d %H:%M:%S')] ❌ Maximum restart limit reached ($MAX_RESTARTS)"
            echo "[$(date '+%Y-%m-%d %H:%M:%S')] Stopping forever script..."
            rm -f "$FOREVER_PID_FILE"
            rm -f "$PID_FILE"
            exit 1
        fi
        
        # Start bot
        echo "[$(date '+%Y-%m-%d %H:%M:%S')] 🔄 Starting bot (attempt $((RESTART_COUNT + 1)))..."
        
        # اجرای ربات (ربات خودش bot.pid را می‌سازد)
        php public/index.php >> "$LOG_FILE" 2>&1
        EXIT_CODE=$?
        
        # بررسی exit code
        if [ $EXIT_CODE -eq 0 ]; then
            echo "[$(date '+%Y-%m-%d %H:%M:%S')] ℹ️  Bot exited normally (exit code: $EXIT_CODE)"
        else
            echo "[$(date '+%Y-%m-%d %H:%M:%S')] ⚠️  Bot crashed (exit code: $EXIT_CODE)"
        fi
        
        # پاک کردن PID file (ربات خودش آن را می‌سازد و پاک می‌کند)
        # اما برای اطمینان، بعد از exit پاک می‌کنیم
        rm -f "$PID_FILE"
        
        # افزایش شمارنده restart
        RESTART_COUNT=$((RESTART_COUNT + 1))
        
        # اگر exit code صفر بود (خروج عادی)، loop را متوقف کن
        if [ $EXIT_CODE -eq 0 ]; then
            echo "[$(date '+%Y-%m-%d %H:%M:%S')] Bot stopped normally. Exiting forever loop."
            break
        fi
        
        # صبر قبل از restart
        echo "[$(date '+%Y-%m-%d %H:%M:%S')] ⏳ Waiting $RESTART_DELAY seconds before restart..."
        sleep $RESTART_DELAY
        
        # پاک کردن process های باقی‌مانده
        kill_all_bot_processes
    done
    
    rm -f "$FOREVER_PID_FILE"
    rm -f "$PID_FILE"
) &

FOREVER_PID=$!
echo $FOREVER_PID > "$FOREVER_PID_FILE"

echo "✅ Forever script started (PID: $FOREVER_PID)"
echo "Log file: $LOG_FILE"
echo ""
echo "To stop:"
echo "  kill $FOREVER_PID"
echo "or:"
echo "  ./stop.sh"
echo ""
echo "To check status:"
echo "  ./status.sh"

