diff --git a/README.md b/README.md index 80e05c7..b094a9f 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ chmod +x install.sh sudo ./install.sh ``` -脚本会把程序安装到 `/opt/server-monitor`,安装 `server-monitor.service`,并立即启动。默认监听 `0.0.0.0:8787`。 +脚本会把程序安装到 `/opt/server-monitor`,安装 `server-monitor.service`,并立即启动。默认监听 `0.0.0.0:8787`。如果仓库本身已经放在 `/opt/server-monitor`,脚本会跳过自我复制,可直接重复运行。 ```bash systemctl status server-monitor --no-pager @@ -226,4 +226,4 @@ sudo rm -f /etc/server-monitor.env ss -lntp | grep 8787 ``` -改用 `--port` 或 systemd drop-in 修改端口。 +改用 `--port` 或 systemd drop-in 修改端口。 \ No newline at end of file diff --git a/install.sh b/install.sh index 79d41ee..1b4bf6a 100755 --- a/install.sh +++ b/install.sh @@ -22,17 +22,35 @@ if ! python3 -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 8) el exit 1 fi -SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" TARGET_DIR="/opt/server-monitor" UNIT_PATH="/etc/systemd/system/server-monitor.service" ENV_PATH="/etc/server-monitor.env" +for required in monitor.py servermon web deploy/server-monitor.service; do + if [[ ! -e "${SOURCE_DIR}/${required}" ]]; then + echo "安装文件不完整,缺少: ${SOURCE_DIR}/${required}" >&2 + echo "请在完整仓库目录中运行安装脚本。" >&2 + exit 1 + fi +done + install -d -m 0755 "${TARGET_DIR}" -install -m 0755 "${SOURCE_DIR}/monitor.py" "${TARGET_DIR}/monitor.py" -rm -rf "${TARGET_DIR}/servermon" "${TARGET_DIR}/web" -cp -a "${SOURCE_DIR}/servermon" "${TARGET_DIR}/servermon" -cp -a "${SOURCE_DIR}/web" "${TARGET_DIR}/web" -install -m 0644 "${SOURCE_DIR}/README.md" "${TARGET_DIR}/README.md" +TARGET_DIR="$(cd "${TARGET_DIR}" && pwd -P)" + +if [[ "${SOURCE_DIR}" == "${TARGET_DIR}" ]]; then + # The repository is already installed at /opt/server-monitor (a common + # deployment). Copying a file onto itself would make install(1) fail and + # deleting the target directories would delete the source we are running + # from, so only install the systemd unit in this case. + echo "当前目录就是安装目录 ${TARGET_DIR},跳过文件复制。" +else + install -m 0755 "${SOURCE_DIR}/monitor.py" "${TARGET_DIR}/monitor.py" + rm -rf "${TARGET_DIR}/servermon" "${TARGET_DIR}/web" + cp -a "${SOURCE_DIR}/servermon" "${TARGET_DIR}/servermon" + cp -a "${SOURCE_DIR}/web" "${TARGET_DIR}/web" + install -m 0644 "${SOURCE_DIR}/README.md" "${TARGET_DIR}/README.md" +fi if [[ ! -f "${ENV_PATH}" ]]; then cat >"${ENV_PATH}" <<'EOF' @@ -55,4 +73,4 @@ echo " 状态: systemctl status server-monitor --no-pager" echo " 日志: journalctl -u server-monitor -f" echo " 认证: 编辑 ${ENV_PATH} 后 systemctl restart server-monitor" echo -systemctl --no-pager --lines=0 status server-monitor.service || true +systemctl --no-pager --lines=0 status server-monitor.service || true \ No newline at end of file