#!/bin/bash
# =====================================================
# AUTO REQUEST APPROVAL BOT - QUICK DEPLOY/UPDATE
# =====================================================
# Usage: sudo ./deploy.sh
# =====================================================

set -e

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

INSTALL_DIR="/var/www/bot"

echo -e "${BLUE}[Deploy] Starting update...${NC}"

cd $INSTALL_DIR

# Pull latest code if git repo
if [ -d ".git" ]; then
    echo -e "${YELLOW}Pulling latest changes...${NC}"
    git pull
fi

# Update dependencies
echo -e "${YELLOW}Updating dependencies...${NC}"
if [ -f "composer.phar" ]; then
    php composer.phar install --no-dev --optimize-autoloader
else
    composer install --no-dev --optimize-autoloader
fi

# Apply any new schema migrations
echo -e "${YELLOW}Checking database...${NC}"
if [ -f ".env" ]; then
    source <(grep -v '^#' .env | sed 's/\r$//' | xargs -d '\n' -I{} echo "export {}")
    mysql -u$DB_USER -p"$DB_PASS" $DB_NAME < schema_install.sql 2>/dev/null || true
fi

# Fix permissions
echo -e "${YELLOW}Fixing permissions...${NC}"
chown -R www-data:www-data $INSTALL_DIR
chmod -R 755 $INSTALL_DIR
chmod 600 $INSTALL_DIR/.env
chmod 777 $INSTALL_DIR/logs

# Restart services
echo -e "${YELLOW}Restarting services...${NC}"
systemctl restart php8.1-fpm
systemctl restart nginx
# Restart cron runner if it exists
if systemctl list-units --full -all | grep -Fq "bot-cron.service"; then
    systemctl restart bot-cron
    echo -e "${GREEN}✓ Cron service restarted${NC}"
fi

# Re-set webhook with correct allowed_updates (ensures chat_member events are received)
if [ -f ".env" ]; then
    BOT_TOKEN=$(grep BOT_TOKEN .env | cut -d '=' -f2 | tr -d '\r')
    if [ ! -z "$BOT_TOKEN" ]; then
        # Get current webhook URL
        WEBHOOK_URL=$(curl -s "https://api.telegram.org/bot${BOT_TOKEN}/getWebhookInfo" | grep -o '"url":"[^"]*"' | cut -d'"' -f4)
        if [ ! -z "$WEBHOOK_URL" ]; then
            echo -e "${YELLOW}Re-setting webhook: ${WEBHOOK_URL}${NC}"
            WEBHOOK_RESPONSE=$(curl -s -X POST "https://api.telegram.org/bot${BOT_TOKEN}/setWebhook" \
                -d "url=${WEBHOOK_URL}" \
                -d 'allowed_updates=["message","callback_query","chat_join_request","my_chat_member","chat_member"]')
            echo -e "${GREEN}✓ Webhook set: ${WEBHOOK_RESPONSE}${NC}"
        else
            echo -e "${YELLOW}⚠ No webhook URL found. Run: php set_webhook.php https://your-domain.com${NC}"
        fi
    fi
fi

echo -e "${GREEN}✓ Deploy complete!${NC}"
