#!/usr/bin/env bash
# vps-manager 自动更新脚本（由 systemd timer 定时触发）
# 从 Gitea 拉取最新代码，如有更新则重启服务
# 部署位置：/opt/vps-manager/deploy/update.sh

set -euo pipefail

cd /opt/vps-manager

git fetch -q origin main

LOCAL=$(git rev-parse HEAD)
REMOTE=$(git rev-parse origin/main)

if [ "$LOCAL" = "$REMOTE" ]; then
  echo "[$(date '+%F %T')] 代码已是最新，无需更新"
  exit 0
fi

echo "[$(date '+%F %T')] 检测到新版本: ${LOCAL:0:8} -> ${REMOTE:0:8}"
git pull --ff-only -q origin main

# 依赖如有变更自动安装（无变化时 pip 会快速跳过）
.venv/bin/pip install -q -r requirements.txt 2>/dev/null || true

# 重启服务加载新代码
systemctl restart vps-manager
echo "[$(date '+%F %T')] 已重启 vps-manager 服务"
