#!/bin/bash
# scripts/setup-monitor.sh
# ═══════════════════════════════════════════════════════════
# 🔧 نصب خودکار مانیتورینگ PM2 + Telegram
# ═══════════════════════════════════════════════════════════

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

echo "═══════════════════════════════════════════"
echo "🔧 PM2 Telegram Monitor - Setup"
echo "═══════════════════════════════════════════"

# ─── چک پیش‌نیازها ───
echo ""
echo "📋 Checking prerequisites..."

for cmd in pm2 node curl crontab; do
    if command -v $cmd &>/dev/null; then
        echo "  ✅ $cmd found"
    else
        echo "  ❌ $cmd NOT found!"
        if [ "$cmd" = "pm2" ]; then
            echo "     Install: npm install -g pm2"
        fi
        exit 1
    fi
done

# ─── دریافت اطلاعات تلگرام ───
echo ""
CONFIG_DIR="$PROJECT_DIR/config"
ENV_FILE="$CONFIG_DIR/telegram.env"
mkdir -p "$CONFIG_DIR"

if [ -f "$ENV_FILE" ]; then
    echo "📄 Config file exists: $ENV_FILE"
    read -p "   Overwrite? (y/N): " OVERWRITE
    if [ "$OVERWRITE" != "y" ] && [ "$OVERWRITE" != "Y" ]; then
        echo "   Keeping existing config."
        source "$ENV_FILE"
    fi
fi

if [ ! -f "$ENV_FILE" ] || [ "$OVERWRITE" = "y" ] || [ "$OVERWRITE" = "Y" ]; then
    echo ""
    echo "🤖 Telegram Bot Setup"
    echo "   (Get token from @BotFather on Telegram)"
    echo ""
    read -p "   Bot Token: " BOT_TOKEN
    read -p "   Chat ID: " CHAT_ID
    read -p "   PM2 App Name [scraper]: " APP_NAME
    APP_NAME=${APP_NAME:-scraper}

    cat > "$ENV_FILE" << EOF
TELEGRAM_BOT_TOKEN="${BOT_TOKEN}"
TELEGRAM_CHAT_ID="${CHAT_ID}"
PM2_APP_NAME="${APP_NAME}"
EOF

    echo "   ✅ Config saved: $ENV_FILE"
fi

# ─── تست ارسال تلگرام ───
echo ""
echo "📨 Testing Telegram connection..."
source "$ENV_FILE"

TEST_RESULT=$(curl -s -w "\n%{http_code}" \
    --max-time 10 \
    -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
    -d "chat_id=${TELEGRAM_CHAT_ID}" \
    -d "parse_mode=HTML" \
    -d "text=🔧 <b>تست اتصال مانیتورینگ</b>

✅ تنظیمات صحیح است!
🖥 سرور: <code>$(hostname)</code>
⏰ $(TZ='Europe/Berlin' date '+%Y-%m-%d %H:%M:%S %Z')
📦 App: <code>${PM2_APP_NAME}</code>

این پیام تستی است. مانیتورینگ فعال می‌شود." 2>&1)

HTTP_CODE=$(echo "$TEST_RESULT" | tail -1)

if [ "$HTTP_CODE" = "200" ]; then
    echo "   ✅ Telegram test PASSED! Check your Telegram."
else
    echo "   ❌ Telegram test FAILED (HTTP $HTTP_CODE)"
    echo "   Please verify Bot Token and Chat ID."
    exit 1
fi

# ─── تنظیم دسترسی‌ها ───
echo ""
echo "🔒 Setting permissions..."
chmod +x "$SCRIPT_DIR/pm2-monitor.sh" 2>/dev/null || true
chmod +x "$SCRIPT_DIR/pm2-heartbeat.sh" 2>/dev/null || true
echo "   ✅ Scripts are executable"

# ─── ایجاد پوشه لاگ ───
mkdir -p "$PROJECT_DIR/logs"

# ─── تنظیم Cron Jobs ───
echo ""
echo "⏰ Setting up cron jobs..."

# حذف cron‌های قبلی مربوط به این پروژه
EXISTING_CRON=$(crontab -l 2>/dev/null || echo "")
CLEAN_CRON=$(echo "$EXISTING_CRON" | grep -v "pm2-monitor.sh" | grep -v "pm2-heartbeat.sh" || true)

# اضافه کردن cron‌های جدید
NEW_CRON="${CLEAN_CRON}

# ═══ PM2 Monitor (every 2 minutes) ═══
*/2 * * * * ${SCRIPT_DIR}/pm2-monitor.sh >> ${PROJECT_DIR}/logs/monitor-cron.log 2>&1

# ═══ PM2 Heartbeat (every 30 minutes) ═══
*/30 * * * * ${SCRIPT_DIR}/pm2-heartbeat.sh >> ${PROJECT_DIR}/logs/heartbeat-cron.log 2>&1
"

echo "$NEW_CRON" | crontab -

echo "   ✅ Cron jobs installed:"
echo "      • Monitor:   every 2 minutes"
echo "      • Heartbeat: every 30 minutes"

# ─── خلاصه ───
echo ""
echo "═══════════════════════════════════════════"
echo "✅ Setup Complete!"
echo "═══════════════════════════════════════════"
echo ""
echo "📁 Files:"
echo "   Config:    $ENV_FILE"
echo "   Monitor:   $SCRIPT_DIR/pm2-monitor.sh"
echo "   Heartbeat: $SCRIPT_DIR/pm2-heartbeat.sh"
echo "   Logs:      $PROJECT_DIR/logs/"
echo ""
echo "🔍 Verify cron:"
echo "   crontab -l"
echo ""
echo "🧪 Manual test:"
echo "   ${SCRIPT_DIR}/pm2-monitor.sh"
echo ""
echo "📊 View logs:"
echo "   tail -f ${PROJECT_DIR}/logs/monitor.log"
echo ""
