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

# Script to run Telegram Bot in background
# Usage: ./start-background.sh

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

cd "$(dirname "$0")"

# Check if .env file exists
if [ ! -f .env ]; then
    echo "Error: .env file not found!"
    exit 1
fi

# Check if PHP is installed
if ! command -v php &> /dev/null; then
    echo "Error: PHP is not installed!"
    exit 1
fi

# PID and log file names
PID_FILE="bot.pid"
LOG_FILE="bot.log"

# بررسی وجود instance های دیگر در حال اجرا (حتی بدون PID file)
EXISTING_PIDS=$(ps aux | grep -E "[p]hp.*public/index\.php" | awk '{print $2}')
if [ -n "$EXISTING_PIDS" ]; then
    echo "⚠️  Warning: Found existing bot processes: $EXISTING_PIDS"
    echo "Killing existing processes to avoid conflicts..."
    for PID in $EXISTING_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
        echo "Force killing remaining processes..."
        for PID in $REMAINING; do
            kill -9 "$PID" 2>/dev/null
        done
        sleep 1
    fi
    rm -f "$PID_FILE"
fi

# Check if bot is already running (double check)
if [ -f "$PID_FILE" ]; then
    OLD_PID=$(cat "$PID_FILE")
    if ps -p "$OLD_PID" > /dev/null 2>&1; then
        echo "Warning: Bot is already running (PID: $OLD_PID)"
        echo "To stop, use:"
        echo "kill $OLD_PID"
        exit 1
    else
        # Old PID exists but process is not running
        rm -f "$PID_FILE"
    fi
fi

echo "Starting bot in background..."

# Run bot in background and save PID
nohup php public/index.php > "$LOG_FILE" 2>&1 &
BOT_PID=$!

# Save PID
echo $BOT_PID > "$PID_FILE"

echo "Bot started successfully!"
echo "PID: $BOT_PID"
echo "Log: $LOG_FILE"
echo ""
echo "To stop the bot:"
echo "  kill $BOT_PID"
echo "or:"
echo "  ./stop.sh"

