#!/usr/bin/bash
set -euo pipefail

# ========= 可调参数 =========
NODE_EXPORTER_VERSION="1.12.1"
NODE_EXPORTER_USER="node_exporter"
INSTALL_DIR="/usr/local/bin"
SERVICE_FILE="/etc/systemd/system/node_exporter.service"
DOWNLOAD_URL="https://github.com/prometheus/node_exporter/releases/download/v${NODE_EXPORTER_VERSION}/node_exporter-${NODE_EXPORTER_VERSION}.linux-amd64.tar.gz"
TMP_DIR="/tmp/node_exporter_install"

# ========= 基础检查 =========
if [[ $EUID -ne 0 ]]; then
  echo "请使用 root 执行此脚本"
  exit 1
fi

if ! command -v systemctl >/dev/null 2>&1; then
  echo "系统不支持 systemctl，无法安装 systemd 服务"
  exit 1
fi

# ========= 系统识别 =========
if [[ -f /etc/os-release ]]; then
  . /etc/os-release
  OS_ID="${ID:-unknown}"
  OS_VERSION_ID="${VERSION_ID:-unknown}"
else
  echo "无法识别系统"
  exit 1
fi

echo "检测到系统：${OS_ID} ${OS_VERSION_ID}"

# ========= 依赖安装（可选） =========
if ! command -v wget >/dev/null 2>&1; then
  echo "未发现 wget，尝试安装..."
  if command -v dnf >/dev/null 2>&1; then
    dnf install -y wget tar
  elif command -v apt-get >/dev/null 2>&1; then
    apt-get update
    apt-get install -y wget tar
  else
    echo "未找到包管理器，且 wget 不存在"
    exit 1
  fi
fi

if ! command -v tar >/dev/null 2>&1; then
  echo "未发现 tar，请先安装 tar"
  exit 1
fi

# ========= 创建用户 =========
if ! id "${NODE_EXPORTER_USER}" >/dev/null 2>&1; then
  useradd --no-create-home --shell /bin/false "${NODE_EXPORTER_USER}"
  echo "已创建用户：${NODE_EXPORTER_USER}"
else
  echo "用户已存在：${NODE_EXPORTER_USER}"
fi

# ========= 下载并安装 =========
mkdir -p "${TMP_DIR}"
cd "${TMP_DIR}"

echo "下载 node_exporter ${NODE_EXPORTER_VERSION} ..."
wget -q -O node_exporter.tar.gz "${DOWNLOAD_URL}"

echo "解压..."
tar xzf node_exporter.tar.gz

echo "安装二进制到 ${INSTALL_DIR} ..."
cp -f "node_exporter-${NODE_EXPORTER_VERSION}.linux-amd64/node_exporter" "${INSTALL_DIR}/node_exporter"
chmod +x "${INSTALL_DIR}/node_exporter"

# ========= 写入 systemd 服务 =========
cat > "${SERVICE_FILE}" <<EOF
[Unit]
Description=Prometheus Node Exporter
After=network-online.target
Wants=network-online.target

[Service]
User=${NODE_EXPORTER_USER}
Group=${NODE_EXPORTER_USER}
Type=simple
ExecStart=${INSTALL_DIR}/node_exporter --web.listen-address=:9100
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF

# ========= 启动服务 =========
systemctl daemon-reload
systemctl enable node_exporter
systemctl restart node_exporter

# ========= 状态检查 =========
echo
echo "安装完成，服务状态如下："
systemctl --no-pager --full status node_exporter || true

echo
echo "监听端口检查："
ss -lntp | grep ':9100' || true
