#!/bin/bash
# Безопасное обновление LMCS-агента (Ubuntu). Запуск: sudo bash update-agent-ubuntu.sh
set -euo pipefail
DIR="$(cd "$(dirname "$0")" && pwd)"
BASE="${LMCS_FILES_BASE:-https://files.th0rn.ru/files/lmcs}"

echo "[1/5] Установка update-infra..."
if [ -f "$DIR/lmcs-run-update.sh" ]; then
  bash "$DIR/install-update-infra.sh" "$DIR"
else
  mkdir -p /usr/local/lib/lmcs
  curl -L -f -s "$BASE/lmcs-run-update.sh" -o /usr/local/lib/lmcs/run-update.sh
  curl -L -f -s "$BASE/lmcs-agent-update.service" -o /etc/systemd/system/lmcs-agent-update.service
  chmod 755 /usr/local/lib/lmcs/run-update.sh
  systemctl daemon-reload
fi

echo "[2/5] Manifest..."
TMP=$(mktemp)
curl -L -f -s "$BASE/agent-manifest.json" -o "$TMP"
SHA=$(python3 -c "import json; print(json.load(open('$TMP'))['ubuntu']['sha256'])")
VER=$(python3 -c "import json; print(json.load(open('$TMP'))['ubuntu'].get('label') or json.load(open('$TMP'))['ubuntu']['version'])")
rm -f "$TMP"

echo "[3/5] Скачивание $VER..."
NEW=/tmp/lmcs-agent-new
curl -L -f -s "$BASE/lmcs-agent" -o "$NEW"
ACT=$(sha256sum "$NEW" | awk '{print $1}')
[ "$ACT" = "$SHA" ] || { echo "SHA mismatch: $ACT != $SHA"; exit 1; }
chmod +x "$NEW"

echo "[4/5] Запуск install job (отдельный systemd unit)..."
printf 'BIN="/usr/bin/lmcs-agent-bin"\nNEW="/tmp/lmcs-agent-new"\n' > /run/lmcs-agent-update.env
systemctl start --no-block lmcs-agent-update.service

echo "[5/5] Ожидание..."
for i in $(seq 1 30); do
  if systemctl is-active --quiet lmcs-agent; then
    echo "OK $VER"
    exit 0
  fi
  sleep 1
done
echo "Таймаут — проверьте: tail -30 /var/log/lmcs-agent-update.log"
exit 1
