#!/bin/bash
# ══════════════════════════════════════════════════════════════
#  PromoBot Installer for cPanel Hosting
#  Usage: bash install.sh
# ══════════════════════════════════════════════════════════════

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

clear
echo -e "${CYAN}══════════════════════════════════════════════════${NC}"
echo -e "${BOLD}   🤖 PromoBot Installer - cPanel Edition${NC}"
echo -e "${CYAN}══════════════════════════════════════════════════${NC}"
echo ""

INSTALL_DIR="$(cd "$(dirname "$0")" && pwd)"
echo -e "${GREEN}📁 Install directory:${NC} $INSTALL_DIR"
echo ""

# ── Step 1: Find Python ──────────────────────────────────────
echo -e "${YELLOW}[1/6]${NC} ${BOLD}Finding Python...${NC}"

PYTHON_BIN=""
for py in python3.12 python3.11 python3.10 python3.9 python3.8 python3; do
    if command -v "$py" &>/dev/null; then
        PYTHON_BIN="$py"
        break
    fi
done

if [ -z "$PYTHON_BIN" ]; then
    echo -e "${RED}❌ Python 3 not found! Contact your hosting provider.${NC}"
    exit 1
fi

PY_VERSION=$($PYTHON_BIN --version 2>&1)
echo -e "${GREEN}✅ Found: $PY_VERSION ($PYTHON_BIN)${NC}"
echo ""

# ── Step 2: Create virtual environment ───────────────────────
echo -e "${YELLOW}[2/6]${NC} ${BOLD}Creating virtual environment...${NC}"

if [ -d "$INSTALL_DIR/venv" ]; then
    echo -e "${CYAN}   venv already exists, removing to recreate...${NC}"
    rm -rf "$INSTALL_DIR/venv"
fi

# Try normal venv first, fall back to --without-pip (cPanel fix)
if $PYTHON_BIN -m venv "$INSTALL_DIR/venv" 2>/dev/null; then
    echo -e "${GREEN}✅ Virtual environment created.${NC}"
else
    echo -e "${YELLOW}   ensurepip not available, using --without-pip...${NC}"
    $PYTHON_BIN -m venv --without-pip "$INSTALL_DIR/venv"
    echo -e "${GREEN}✅ Virtual environment created (without pip).${NC}"
    
    # Install pip manually via get-pip.py
    echo -e "${YELLOW}   Downloading pip...${NC}"
    curl -sS https://bootstrap.pypa.io/get-pip.py -o "$INSTALL_DIR/get-pip.py"
    "$INSTALL_DIR/venv/bin/python" "$INSTALL_DIR/get-pip.py" -q
    rm -f "$INSTALL_DIR/get-pip.py"
    echo -e "${GREEN}✅ pip installed manually.${NC}"
fi
echo ""

# ── Step 3: Install dependencies ─────────────────────────────
echo -e "${YELLOW}[3/6]${NC} ${BOLD}Installing dependencies...${NC}"

source "$INSTALL_DIR/venv/bin/activate"
pip install --upgrade pip -q 2>/dev/null || true
pip install -r "$INSTALL_DIR/requirements.txt"
echo -e "${GREEN}✅ Dependencies installed.${NC}"
echo ""

# ── Step 4: Configure .env ───────────────────────────────────
echo -e "${YELLOW}[4/6]${NC} ${BOLD}Configuring bot settings...${NC}"

if [ -f "$INSTALL_DIR/.env" ]; then
    echo -e "${CYAN}   .env file already exists.${NC}"
    read -p "   Overwrite? (y/N): " OVERWRITE
    if [[ ! "$OVERWRITE" =~ ^[Yy]$ ]]; then
        echo -e "${CYAN}   Keeping existing .env${NC}"
        SKIP_ENV=1
    fi
fi

if [ -z "$SKIP_ENV" ]; then
    echo ""
    echo -e "${BOLD}   Enter your bot settings:${NC}"
    echo ""
    
    read -p "   🔑 Bot Token (from @BotFather): " BOT_TOKEN
    read -p "   👤 Your Telegram User ID (comma-separated for multiple admins): " ADMIN_IDS
    read -p "   🔗 Main Bot URL (e.g. https://t.me/YourMainBot): " MAIN_BOT_URL
    read -p "   📢 Channel URL (e.g. https://t.me/YourChannel): " CHANNEL_URL

    cat > "$INSTALL_DIR/.env" << ENVEOF
BOT_TOKEN=$BOT_TOKEN
ADMIN_IDS=$ADMIN_IDS
MAIN_BOT_URL=$MAIN_BOT_URL
CHANNEL_URL=$CHANNEL_URL
ENVEOF

    chmod 600 "$INSTALL_DIR/.env"
    echo -e "${GREEN}✅ .env configured and secured.${NC}"
fi
echo ""

# ── Step 5: Create management script ─────────────────────────
echo -e "${YELLOW}[5/6]${NC} ${BOLD}Creating management script...${NC}"

cat > "$INSTALL_DIR/bot.sh" << 'SHEOF'
#!/bin/bash
# PromoBot management script
DIR="$(cd "$(dirname "$0")" && pwd)"
PIDFILE="$DIR/bot.pid"
LOGFILE="$DIR/bot.log"
PYTHON="$DIR/venv/bin/python"

start() {
    if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
        echo "🤖 Bot is already running (PID: $(cat $PIDFILE))"
        return
    fi
    echo "🚀 Starting bot..."
    nohup $PYTHON "$DIR/bot.py" >> "$LOGFILE" 2>&1 &
    echo $! > "$PIDFILE"
    sleep 2
    if kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
        echo "✅ Bot started (PID: $(cat $PIDFILE))"
        echo "📄 Logs: tail -f $LOGFILE"
    else
        echo "❌ Bot failed to start. Check logs:"
        tail -20 "$LOGFILE"
        rm -f "$PIDFILE"
    fi
}

stop() {
    if [ ! -f "$PIDFILE" ]; then
        echo "⚠️  Bot is not running (no PID file)"
        return
    fi
    PID=$(cat "$PIDFILE")
    if kill -0 "$PID" 2>/dev/null; then
        echo "🛑 Stopping bot (PID: $PID)..."
        kill "$PID"
        sleep 2
        if kill -0 "$PID" 2>/dev/null; then
            kill -9 "$PID"
        fi
        echo "✅ Bot stopped."
    else
        echo "⚠️  Bot was not running."
    fi
    rm -f "$PIDFILE"
}

restart() {
    stop
    sleep 1
    start
}

status() {
    if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
        echo "🟢 Bot is running (PID: $(cat $PIDFILE))"
    else
        echo "🔴 Bot is not running."
        rm -f "$PIDFILE" 2>/dev/null
    fi
}

logs() {
    if [ -f "$LOGFILE" ]; then
        tail -50 "$LOGFILE"
    else
        echo "No logs yet."
    fi
}

case "$1" in
    start)   start ;;
    stop)    stop ;;
    restart) restart ;;
    status)  status ;;
    logs)    logs ;;
    *)
        echo "Usage: bash bot.sh {start|stop|restart|status|logs}"
        exit 1
        ;;
esac
SHEOF

chmod +x "$INSTALL_DIR/bot.sh"
echo -e "${GREEN}✅ Management script created (bot.sh)${NC}"
echo ""

# ── Step 6: Setup auto-restart cron ──────────────────────────
echo -e "${YELLOW}[6/6]${NC} ${BOLD}Setting up auto-restart (cron)...${NC}"

CRON_CMD="@reboot cd $INSTALL_DIR && bash bot.sh start"
CRON_CHECK="*/5 * * * * cd $INSTALL_DIR && bash bot.sh status | grep -q 'not running' && bash bot.sh start >> $INSTALL_DIR/cron.log 2>&1"

# Check if cron already set
EXISTING_CRON=$(crontab -l 2>/dev/null || true)
if echo "$EXISTING_CRON" | grep -q "promobot/bot.sh"; then
    echo -e "${CYAN}   Cron jobs already exist, skipping...${NC}"
else
    read -p "   Add auto-restart cron jobs? (Y/n): " ADD_CRON
    if [[ ! "$ADD_CRON" =~ ^[Nn]$ ]]; then
        (echo "$EXISTING_CRON"; echo "# PromoBot auto-restart"; echo "$CRON_CMD"; echo "$CRON_CHECK") | crontab -
        echo -e "${GREEN}✅ Cron jobs added:${NC}"
        echo -e "   ${CYAN}• Auto-start on server reboot${NC}"
        echo -e "   ${CYAN}• Health check every 5 minutes${NC}"
    else
        echo -e "${CYAN}   Skipped cron setup.${NC}"
    fi
fi
echo ""

# ── Done! ─────────────────────────────────────────────────────
echo -e "${CYAN}══════════════════════════════════════════════════${NC}"
echo -e "${GREEN}${BOLD}   ✅ Installation Complete!${NC}"
echo -e "${CYAN}══════════════════════════════════════════════════${NC}"
echo ""
echo -e "${BOLD}   Management Commands:${NC}"
echo -e "   ${CYAN}bash bot.sh start${NC}    → Start the bot"
echo -e "   ${CYAN}bash bot.sh stop${NC}     → Stop the bot"
echo -e "   ${CYAN}bash bot.sh restart${NC}  → Restart the bot"
echo -e "   ${CYAN}bash bot.sh status${NC}   → Check if running"
echo -e "   ${CYAN}bash bot.sh logs${NC}     → View recent logs"
echo ""

read -p "🚀 Start the bot now? (Y/n): " START_NOW
if [[ ! "$START_NOW" =~ ^[Nn]$ ]]; then
    bash "$INSTALL_DIR/bot.sh" start
fi
