#!/bin/bash
NEXIOS_URL="https://nexios.ru"
INSTALL_DIR="/opt/xnexx-agent"
AGENT_PATH="$INSTALL_DIR/xnexx-agent"
TEMP_AGENT="/tmp/xnexx-agent.new"
LOG_FILE="/var/log/xnexx-agent-update.log"
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}
if [ "$EUID" -ne 0 ]; then 
    log "ERROR: Запустите от root"
    exit 1
fi
log "Проверка обновлений агента..."
if [ -f "$AGENT_PATH" ]; then
    CURRENT_MD5=$(md5sum "$AGENT_PATH" | awk '{print $1}')
else
    log "ERROR: Агент не найден в $AGENT_PATH"
    exit 1
fi
REMOTE_MD5=$(curl -sf "$NEXIOS_URL/xnexx/xnexx-agent.md5" || echo "")
if [ -z "$REMOTE_MD5" ]; then
    log "WARNING: Не удалось получить MD5 с сервера"
    exit 0
fi
REMOTE_MD5=$(echo "$REMOTE_MD5" | awk '{print $1}')
if [ "$CURRENT_MD5" = "$REMOTE_MD5" ]; then
    log "Агент актуален"
    exit 0
fi
log "Новая версия, обновляем..."
if ! curl -sf -o "$TEMP_AGENT" "$NEXIOS_URL/xnexx/xnexx-agent"; then
    log "ERROR: Не удалось скачать"
    exit 1
fi
NEW_MD5=$(md5sum "$TEMP_AGENT" | awk '{print $1}')
if [ "$NEW_MD5" != "$REMOTE_MD5" ]; then
    log "ERROR: MD5 не совпадает"
    rm -f "$TEMP_AGENT"
    exit 1
fi
systemctl stop xnexx-agent
cp "$AGENT_PATH" "$AGENT_PATH.backup.$(date +%Y%m%d_%H%M%S)"
mv "$TEMP_AGENT" "$AGENT_PATH"
chmod +x "$AGENT_PATH"
systemctl start xnexx-agent
sleep 3
if systemctl is-active --quiet xnexx-agent; then
    log "SUCCESS: Обновлён (MD5: $NEW_MD5)"
    ls -t "$AGENT_PATH.backup."* 2>/dev/null | tail -n +4 | xargs rm -f 2>/dev/null
else
    log "ERROR: Не запустился, откат..."
    LATEST_BACKUP=$(ls -t "$AGENT_PATH.backup."* 2>/dev/null | head -n 1)
    if [ -n "$LATEST_BACKUP" ]; then
        cp "$LATEST_BACKUP" "$AGENT_PATH"
        systemctl start xnexx-agent
    fi
    exit 1
fi
